为什么我最后的cout中的第一个字母会被切断
How come the first letter in my final cout gets cut off?
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
.
相关文章:
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 获取每个目录或子目录中第一个文件的路径
- 程序没有问 3 个问题,而是将我对第一个问题的回答用于其他两个问题
- 为什么 Boost multi_index只修改第一个索引的键时对第二个索引进行比较?
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 为什么指向矢量第一个元素的指针会丢失?
- 链表中头/第一个节点的声明
- 第一个任务的代码在 RTOS 中切换
- 如何通过 std::apply 调用具有定义的第一个参数的可变参数模板函数?
- 按第一个值的递减顺序对一组对进行排序,然后按第二个值的字母顺序排序
- 指向数组的指针是否应该等于指向其第一个元素的指针?
- 当字符串中只有一个"GOOD"字符串可用时,从没有空格的字符串中提取第一个单词的最佳和有效方法?
- 如何获取指向 qsort 第一个参数的向量中第一项的指针?
- 数组不会存储超出第一个空间的范围
- 为什么这段代码给出错误......'a'是指针到字符指针,应该存储's'的地址,因为s是指向数组的第一个元素的指针
- 如何检索向量中第一个找到的值最低的元素
- 获取第 n 项与 std::set 中第一个/最后一个的偏移量