读取 C++ 中的输入

Read input in c++

本文关键字:输入 C++ 读取      更新时间:2023-10-16

我对 c++ 非常陌生,并试图迈出我的第一步。在我的问题中,我需要读取 3 个整数并对其进行处理。所以,为了取这个整数,我写了:

int a, b, n;
scanf("%i%in", &a, &b);
scanf("%i", &n);

我也尝试过:

scanf("%i%i", &a, &b);
scanf("%i", &n);

但他总是给我一些随机的大整数。输入:

7 13
1

如果我写

freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b, n;
cin >> a >> b;
cin >> n;
printf("%i", n);
return 0;

它不起作用。与

freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b, n;
scanf("%i%i", &a, &b);
scanf("%i", &n);    
printf("%i", n);
return 0;
这不是

在C++中输入整数的方式。 尝试:

std::cin >> a >> b >> c;

但是如果你想在第一行有两个,第三行在单独的一行,您可能需要逐行阅读(使用 std::getline ):

std::string line;
std::getline( std::cin, line );
std::istringstream l1( line );
l1 >> a >> b >> std::ws;
if ( !l1 || l1.get() != EOF ) {
    //  The line didn't contain two numbers...
}
std::getline( std::cin, line );
std::istringstream l2( line );
l2 >> n >> std::ws;
if ( !l2 || l1.get() != EOF ) {
    //  The second line didn't contain one number...
}

这将允许更好的错误检测和恢复(假设输入格式是面向行的)。

您可能应该忘记scanf. 很难使用正确,而且不是很灵活。

如果您使用的是C++,是否有理由不使用流?

std::cin >> a >> b;
std::cin >> n;

要从文件中读取,您将使用 std::ifstream。

std::ifstream file( "filename.txt" );
if( file.is_open() )
{
    file >> a >> b >> n;
    file.close();
}

cppreference.com 是一个很好的参考:ifstream