如何解决C ++逐行读取文本文件
我想读取一个txt文件,并且想要一个一行地处理每个数字,应用一些功能并传递给另一行。该行结束后,我不知道如何对下面的行应用相同的操作。方法将从每一行获得不同的输出,这就是为什么我必须分别处理每一行的原因。
int number;
ifstream readingFile("a.txt");
while(readingFile >> number){
/* Methods will be applied to each number in the line */
}
readingFile.close();
a.txt
23 4 555
2123 44 21 4
1 45 667 2 112
解决方法
工作的C ++代码
清除疑问,在https://www.tutorialspoint.com/compile_cpp11_online.php中进行测试 只需复制粘贴执行
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
int main ()
{
//code create a file with numbers
std::ofstream myfile;
myfile.open ("file.txt");
myfile << "123 12 32323\n 4444 55 535\n";
myfile.close();
std::ifstream input( "file.txt" );
for( std::string eachLine; getline( input,eachLine ); )
{
std::istringstream strm(eachLine);
std::string splitedLines;
// loop for each string and add to the vector
while ( strm >> splitedLines )
{
std::stringstream geek(splitedLines);
int num; // can be int,float or double
geek >>num;
//perform action on all num in each line one by one
std::cout<<num<<std::endl;
}
}
return 0;
}
编辑: PythonCode 读取每一行中的数字
fileName = open('a.txt','r')
line = fileName.readline() //reading first line
while(line):
for eachStringNumber in line.split():
number = int(eachStringNumber)
/// Methods will be applied to each number in the line ///
line = fileName.readline() // reading lines one by one in each loop
fileName.close()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。