从文件读取 C++ 程序停止工作

Read from file c++ program stops working

我正在尝试从 C++ 中的文本文件中读取,文本文件的格式如下:

1 2
5 3
4 6

我的代码如下所示:

std::string line;
    std::ifstream infile("thefile.txt");
    int a, b;
    while (infile >> a >> b)
    {
        printf("%s, %s", a, b);
    }

但是每次我尝试 运行 我的代码时程序停止工作,我一直跟踪它直到 while 循环,所以代码在 while 循环之前工作正常,我不明白为什么。请指教

您在 printf 中使用了错误的格式说明符。使用

printf("%d, %d", a, b);

要使输出看起来更像输入,请使用:

printf("%d %d\n", a, b);

std::cout << a << " " << b << std::endl;
    #include <iostream>
    #include <fstream>
    using namespace std;

    int main()
    {
        std::string line;
        std::ifstream infile("thefile.txt");
        int a = 0, b;
        while (infile >> a >> b)
        {
//The correction was made in this line
// Org code -printf("%s %s", a,b); -- You wanted to print integers but 
// but informed the compiler that strings will be printed.
            printf("%d %d", a,b);
            printf("\n");
        }

        return 0;
    }