这个程序在使用存档输入C++有什么问题?

What's wrong with this program in C++ using an archive input?

本文关键字:C++ 输入 什么 问题 程序      更新时间:2023-10-16

>我有以下代码C++:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
    int N;
    string s;
    char str[100];
    scanf("%d",&N);
    for(int i=0; i<N; i++)
    {
        fflush(stdin);
        fgets(str,100,stdin);
        s = str;
        cout << s << endl;
    }
    return 0;
}

代码保存在存档测试中.cpp。

在 Linux Ubuntu 上使用终端进行编译:

g++ -c hello.cpp
g++ -o hello hello.o

我有一个存档 test.in,它将作为输入:

5
God of War
Grand Theft Auto
The Smurfs
Final Fantasy
Call of Duty

在终端中运行命令:

./test < test.in

输出将是:

rogerio@rogerio-Aspire-5741Z:~/Documentos$ ./teste < teste.in

God of War
Grand Theft Auto
The Smurfs
Final Fantasy
rogerio@rogerio-Aspire-5741Z:~/Documentos$

因为《使命召唤》这条线跳了?

scanf("%d",&N);

不会跳过行尾,因此第一个fgets(str,100,stdin);只读取给出5的行的其余部分。注意输出中多余的空行,因为它已经发布?