gpt4 book ai didi

C++ std::cin 产生额外的输入

转载 作者:搜寻专家 更新时间:2023-10-31 00:34:59 25 4
gpt4 key购买 nike

我是 C++ 的新手,正在尝试解决一些基本的 CodeJam 问题。我正在研究 Reverse Words .我通过管道输入和输出已编译的可执行文件来运行我的代码(在 unix 环境中): ./compiled.program < input_file.in > output_file.out

这是我的输入(input_file.in):

3
this is a test
foobar
all your base

我会期望输出:

test a is this
foobar
base your all

但是,我得到了输出(output_file.out):


test a is this
foobar

(是的,开头的空格是故意的)

这是我的源代码:

#include <string>                                                                                                           
#include <iostream>

int main()
{
int number_of_cases;
std::cin >> number_of_cases;

for (int i=1; i<=number_of_cases; i++) {
std::cerr << i << std::endl;

std::string input = "";
std::getline(std::cin, input);

while (true) {
int pos = input.find_last_of(" ");
if (pos == -1) {
std::cout << input;
break;
}
std::cout << input.substr(pos+1)+" ";
input.resize(pos);
}
std::cout << std::endl;
}
return 0;
}

对我来说,问题似乎是从 3 之间读取另一个输入源(空白输入源)。和 this is a test但对于我的生活,我无法找出原因。这就是我的问题:为什么要从其他输入源读取数据?

非常感谢任何帮助。非常感谢您!

最佳答案

线

std::cin >> number_of_cases; 

读入3但停在那里,将换行符留在流中。

所以对于 i == 1 , std::getline(std::cin, input);只是从第一行的末尾读取换行符。由于这不包含空格,因此您触发了 std::cout << input;然后分解为 std::cout << std::endl , 生成你的空白行。

然后是3的计数在到达 all your base 之前用完了.

要解决此问题,您可以对 getline 进行虚拟调用在进入循环之前(这也有消耗任何尾随空格的好处)。

关于C++ std::cin 产生额外的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24926355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com