简体   繁体   English

FStream-读取文件C ++中的整数

[英]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. 但是,由于某种原因,我似乎无法将字符串行强制转换为int。 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: txt文件:

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. 请参阅参考文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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