How to read numbers separated by commas in c ++?

2

I hope you are well.

I would like you to help me please read numbers separated by commas in C ++ language, I know that java uses the split function but I am new to c ++ and I do not know how to do it.

It is to be added to a matrix with its transpose, for example:

If the user enters: 1,2,3,4,5,6,7,8,9

the matrix is:

1 2 3
4 5 6 
7 8 9

and its transpueesta is:

1 4 7
2 5 8
3 6 9

I've done it this way:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()

{
    int i;//Variable to columns of the matrix
    int j;//Variable to rows of the matrix
    int n;//Variable to define the matrix
    int numero;
    cout<< "Defina el tamaño de la matriz"<<endl;



    cin>>n;//Read the length of the matrix
    int matriz[n][n];
    cout<<"Introduzca los numeros: ";

    for(i =0; i<n;i++)
    {
        for(j=0; j<n;j++)
        {
            cin>>numero;//Read the numbers in the console.
            matriz[i][j]=numero;//Add to the matrix the numbers
        }

    }

    cout<<"La matriz original es"<<endl;

    //Print the original matrix
    for(i =0; i<n;i++)
    {
            for(j=0; j<n;j++)
            {
                cout<<matriz[i][j]<<" ";
            }
               cout<<""<<endl;
    }

    cout<<"La transpuesta de esta matriz es"<<endl;

    //Print the transpose of the matrix
    for(i =0; i<n;i++)
    {
            for(j=0; j<n;j++)
            {
                cout<<matriz[j][i]<<" ";
            }
                 cout<<""<<endl;
     }

    return 0;

    }

But I can not get the numbers to be entered by commas, but read them in a common way (1 enter, 2 enter, 3 enter ...)

Thanks in advance.

    
asked by Yesith 05.12.2017 в 17:34
source

3 answers

2

If the user enters the numbers such that 1,2,3,... the reading can be as simple as the code that follows:

for(int i=0; i<n;i++)
{
    for(int j=0; j<n;j++)
    {
        cin>>matriz[i][j];   // Se lee el numero
        cin.ignore(1); // Se descarta el separador
    }
}

However, note that using cin , the sequence will not be processed until a line break is entered ( enter so that we understand each other).

Regarding the problems of your code, I refer to the response of @PaperBirdMaster

    
answered by 05.12.2017 / 18:26
source