C++文本文件的获取线

C++ getline for text file

本文关键字:获取 文件 文本 C++      更新时间:2023-10-16

我希望真的很简单。我已经打开了一个文本文件,我希望它使用 getline 读取第一行。我希望它采用该行中的所有整数,用逗号分隔,并将它们加在一起以存储在变量中。但是,我不太确定如何使用分隔符进行设置。

#include <fstream>
#include <iostream>
int main(){
std::fstream codeBreaker;
int x,y,z;
codeBreaker.open("input.txt");
void decipher();
void encode();
std::cout << "Have a nice day!" << std::endl;
return 0;
}
void decipher(){
}
void encode(){
}

您已经概述了第一步:在第一行中阅读std::getline.你错过的一点是,几乎每当你读取数据时,你都想检查读取是否成功。

std::string line;
if (std::getline(infile, line))
// we got some data
else
// the read failed

从那里,您需要将该行解析为单个数字。一种方法是stringstream.

std::stringstream buffer(line);

由于您的数字用逗号分隔,因此您需要读取(但忽略(逗号,然后读取下一个数字。继续直到到达行尾,您通常会通过检查读取数字是否成功来发现。

int number;
while (buffer >> number) {
char ch;
buffer.get(ch);
if (ch != ',')
// unexpected input ?
// do something with the number we just read here
}