C++ programming I/O

C++ programming I/O

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

我正试图从包含1000条记录的文本文件中获取输入。

    10
  • 100
  • 101
  • 3 123
  • 124
  • 1234年
  • 1000

我使用下面的代码在三个变量中输入d=10(文本文件的第一行,a包含第一列的所有数字,b包含第二列的所有数字)

我在这段代码中遇到的问题是,它将文件的后半部分作为输入,而忽略前半部分。

输出:

    3211年
  • 500
  • 3212年
  • 501
  • 22121年
  • 502
  • 1000 1234

        char fileName[20];
        cout << "Enter input test file name: ";
        cin >> fileName;
        ifstream readFile;              //object of input file stream
        readFile.open(fileName);        //open a file
                                        //Check for an error
        if (readFile.fail())
        {
            cerr << "Error Opening File" << endl;
        }
        string c, d,a,b;
        getline(readFile, c);
        for (int i=0; i<1000;i++)
        {
            getline(readFile, readLine);
            istringstream split(readLine);
            getline(split, a);
            getline(split, b);
            cout <<serverNum<<" "<<a<<" "<<b<<endl;
        }
    

谁能告诉我为什么我面对这个

更好的方法是:

#include <iostream> // std::cout, std::endl
#include <fstream>  // std::ifstream
using namespace std;
int main()
{
    // open your file
    ifstream input_file("test.txt");
    // create variables for your numbers
    int first_num, left_num, right_num;
    // determine the first number in your file
    input_file >> first_num;
    // while there is a number on the left, put that number into left_num
    while(input_file >> left_num)
    {
        // put the corresponding right number into right_num
        input_file >> right_num;
        // now you can work with them
        cout << left_num << ' ' << right_num << endl;
    }
   // close the file
   input_file.close();
   return 0;
}
<标题>编辑:

@Syed问题可能是你的命令行没有足够的缓冲,只是覆盖了你之前的500行。打开cmd,点击左上角,进入设置,布局,增加缓冲区。代码可以工作,它必须是你的控制台。

还因为您回答了包含浮点数的列表,您可能要考虑将left_numright_numint更改为floatdouble