读取 C++ 中的输入
Read input in c++
我对 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
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type