gpt4 book ai didi

c++ - 为什么我的字符串第二次没有正确接受输入?

转载 作者:行者123 更新时间:2023-11-27 23:59:05 26 4
gpt4 key购买 nike

我的代码采用一个字符串并显示偶数索引位置字母,然后在空格后显示奇数索引字母。就像如果我给一个输入 Hacker 它应该给 Hce akr。现在我的代码没有给我第二个输入的正确答案。就像将第二个输入作为 Rank 一样,它应该给出 Rn ak。相反,它给出了 k 。这里它错过了 R


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void f(string a) {

string odd,even;
for(int i=0; a[i] != '\0'; i++) {
if(i % 2 == 0) {
even = even + a[i];
} else {
odd = odd + a[i];
}
}

cout << even << " " << odd << "\n";//<<<<<<I THINK THIS \n IS THE

//PROBLEM BUT I NEED THIS \n.I OBESERVED THAT ON REMOVING \n, CODES
// WORKS CORRECTLY.
}

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string str;
int t;
cin >> t;

for(int i=0; i < t; i++) {
std::cin.ignore();
getline(cin, str);
f(str);
}

return 0;
}

最佳答案

您应该将 std::cin.ignore() 移到循环之外。getline 消耗换行符,只有第一个输入离开它 (cin>>t)。

当您阅读例如int 或 char,输入后的换行符保留在输入流中。因此,现在执行 getline 只会读取换行符,然后调用 cin.ignore() 来使用换行符。但是随后每个 getline() 都会消耗整行,包括换行符,因此您不必调用 cin.ignore(),如果您这样做,它会默认占用一个字符,此处为“R”。

关于c++ - 为什么我的字符串第二次没有正确接受输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40487799/

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