gpt4 book ai didi

c++ - 为什么我最后的 cout 中的第一个字母被截断了?

转载 作者:太空狗 更新时间:2023-10-29 20:55:32 26 4
gpt4 key购买 nike

int main () {
const int MAX_INPUT = 99;
string names[MAX_INPUT];
string eraseName;
string newList;
int numNames = 0;
int i = 0;


cout << "How many names do you want (max 99)? ";
cin >> numNames;

do {
if(numNames > MAX_INPUT) {
cout << "Out of memory!" << endl;
break;
}
cout << "Enter name #" << (i+1) << ": ";
cin.ignore();
getline(cin,names[i]);
++i;
}
while (i < numNames);

cout << "What name do you want to eliminate? ";
getline(cin,eraseName);
cout << "Here is the list in reverse order, skipping ";
cout << eraseName << "..." << endl;

i = 0;
for (i = 0; i < numNames; ++i) {
cout << names[i] << endl;
}
return 0;
}

我有一个任务,我必须“消除”数组中的一个元素并重新创建输出。我知道我的最终 for 循环不会删除该元素,它就在那里因为我正在测试这个问题,但是如果名称有两个输入(John Doe 和 Jane Doe)并且我说要 cout 他们最后的循环 couts:

李四
母鹿

最佳答案

cin.ignore() 移到 cin >> numNames; 之后,在读取名称的循环之前。

你只需要这个来忽略读取名称数量后留在流中的换行符。 getline() 从流中读取(并忽略)换行符,因此在读取每个名称之前无需再次调用 ignore()。结果,它读取并忽略了名称的第一个字符。

关于c++ - 为什么我最后的 cout 中的第一个字母被截断了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463279/

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