C++ - Using stringstream object to read strings and integers from a sentence in an external txt file

StackOverflow https://stackoverflow.com/questions/18767328

  •  28-06-2022
  •  | 
  •  

Pregunta

I tried to retrieve the integers from a txt file and adding them up to get the total. I did this using stringstream class. The string of the text is:- 100 90 80 70 60. The code to extract the integers and add them is as follows:-

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
    ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
    stringstream sstr;
    string from_file;
    int grade;
    int total = 0;
    getline(inFile,from_file);
    sstr<<from_file;
    while(sstr
    {
        sstr>>grade;
        cout<<grade<<endl;
        total+=grade;
    }
    cout<<total<<endl;
    inFile.close();
    return 0;
}

This code works fine. After this, I modify the string in the file as 'the grades you scored are 100 90 80 70 60`. Now, if try to run the above code, I get the output as:-

0
0
0
0
0
0

Can you please help me and tell me how to calculate the total in the latter case ? Also, here I know the number of integers in the files. What about the case when I don't know the number of grades in the file?

¿Fue útil?

Solución

Because "the grades you scored are " is the head part of your stringstream.

You cannot get read an int from it. It'll just give you a 0

You may read to some string as "Entry" and parse the Entry by writing some functions.

Otros consejos

I'll be answering the second part of the question i.e. reading inputs without knowing the total number of inputs:-

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
    ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
    string data;
    int grades,total=0;
    getline(inFile,data);
    stringstream sstr;
    sstr<<data;
    while(true)
    {
        sstr>>grades;   
        if(!sstr)
            break;
        cout<<grades<<endl;
        total+=grades;
    }
    cout<<total<<endl;
    return 0;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top