【问题标题】:C++ Reading text file line by lineC++逐行读取文本文件
【发布时间】:2020-08-15 20:51:14
【问题描述】:

我想读取一个 txt 文件,我想一个一个地处理行上的每个数字,应用一些函数并传递到另一行。当行结束时,我不知道如何对下面的行应用相同的操作。方法将从每一行得到不同的输出,这就是我必须分别处理每一行的原因。

int number;
ifstream readingFile("a.txt");

while(readingFile >> number){
    /* Methods will be applied to each number in the line */
}

readingFile.close();

一个.txt

23 4 555

2123 44 21 4

1 45 667 2 112

【问题讨论】:

标签: c++ methods while-loop line ifstream


【解决方案1】:

工作 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()

【讨论】:

  • 问题是关于c++的,请不要回答错误的语言或标准,超过20年。请为 c++11 重写你的答案
  • 抱歉在开头添加了 Python 代码
  • 好吧, 都可以工作,但 仍然更加 c++ 热情,因此更新了。
  • 一次性将数字保存在向量中、逐行保存或整个文件中。
猜你喜欢
  • 2020-09-11
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多