简体   繁体   中英

FStream - Reading Integers inside file C++

The objective is to read each integer in the following file and add them all up. But it seems I cannot cast the string line to an int for some reason. Code:

#include <iostream>
#include <fstream>
using namespace std;

int main(){

string line;
ifstream file ("Random.txt");
int lines;
int amount = 0;
while(getline(file, line)){
    lines++;
    amount += static_cast<int>(line);
}

cout << amount; 
return 0;

}

Txt file:

2
3
4
6

Any help would be much appreciated

No, you can't cast a string like that to anything, really.

If you know that the file contains only integers, you can just read them directly:

int   number;
while (file >> number)
{
    ++lines;
    amount += number;
}

A cast isn't the right tool to do so, it works for compatible types only.

What you actually need is a conversion function:

amount += std::stoi(line);

See the reference docs please.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM