Search code examples
c++arraysfileiostringstream

When converting a string array of numbers to an array of integers the elements are turned to 0s


When I convert info to integers and print out the array, the output is just 0s. Each element in info is a number entered as a string that was taken from a text file. For example: 513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79. I used strtok to remove the spaces from the line and enter the numbers into info. When I print out info all of the numbers are there. How do I get these to convert properly?

string info[1000]
int student[18];
for (int i=1; i<18; i++){
    //cout << info[i] << endl;
    stringstream convert(info[i]);
    convert << student[n];
    cout << student[n] << endl;
    n++;
}

Solution

  • String Streams are my favorite tool for this. They automatically convert data types (most of the time) just like cin and cout do. Here is an example with a string stream. They are included in the library

    string info = "513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79";
    int student[18];
    
    stringstream ss(info);
    
    for (int i=0; i< 18; i++){
       ss >> student[i];
       cout << student[i] << endl;;
    } 
    

    And here is a repl https://repl.it/J5nQ