为什么我最后的cout中的第一个字母会被切断

How come the first letter in my final cout gets cut off?

本文关键字:第一个 最后的 cout 为什么      更新时间:2023-10-16
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(,我说要将它们归结为最终循环 couts:

无名氏
安·多伊

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

您只需要它来忽略读取名称数后流中剩余的换行符。 getline()从流中读取(并忽略(换行符,因此在读取每个名称之前无需再次调用ignore()。因此,它会读取并忽略名称的第一个字符。

以下代码块

if(numNames > MAX_INPUT) {
   cout << "Out of memory!" << endl;
   break;
 }  

不需要在 do-while 循环的每次迭代中执行。您可以更改函数以使用:

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

将检查移出循环后,您必须问自己:"我是否需要忽略循环的每次迭代中的字符?答案是否定的。只有在阅读numNames后,您才需要忽略换行符。因此,您也可以将其移出循环。

if(numNames > MAX_INPUT) {
   cout << "Out of memory!" << endl;
   // Deal with the problem. Exit??
}
// Ignore the newline left on the stream before reading names.
cin.ignore();
do {
    cout << "Enter name #" << (i+1) << ": ";
    getline(cin,names[i]);
    ++i;
}  while (i < numNames);

您可以通过使用以下方法确保忽略包括换行符在内的所有内容来改进这一点:

cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

#include <limits>

能够使用std::numeric_limits.

相关文章: