C++ 我期末考试的第一个字母怎么会被剪掉? int main(){ 常量int MAX_输入=99; 字符串名称[最大输入]; 字符串名称; 字符串newList; int numNames=0; int i=0; cout>numNames; 做{ 如果(数值>最大输入){ cout
移动C++ 我期末考试的第一个字母怎么会被剪掉? int main(){ 常量int MAX_输入=99; 字符串名称[最大输入]; 字符串名称; 字符串newList; int numNames=0; int i=0; cout>numNames; 做{ 如果(数值>最大输入){ cout,c++,C++,移动cin.ignore()就在cin>>numNames;之后,读取名称的循环之前 您只需要这样做就可以忽略读取名称数后留在流中的换行符。getline()从流中读取(并忽略)换行符,因此无需调用ignore()再次读取每个名称。因此,它正在读取并忽略名称的第一个字符。下面的代码块 int main () { const int MAX_INPUT = 99; string names[MAX_INPUT]; string eraseName; string n
cin.ignore()
就在cin>>numNames;
之后,读取名称的循环之前
您只需要这样做就可以忽略读取名称数后留在流中的换行符。
getline()
从流中读取(并忽略)换行符,因此无需调用ignore()
再次读取每个名称。因此,它正在读取并忽略名称的第一个字符。下面的代码块
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;
}
一旦您将签出循环,您必须问自己,“是否需要在循环的每次迭代中忽略一个字符?”答案是“否”。只有在读取numNames
后才需要忽略换行符。因此,您也可以将其移出循环
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);
if(numNames>MAX\u输入){
你为什么把cin.ignore()
在那里?你试过把它放在别的地方吗?如果你输入3个或更多的名字会发生什么?哪些名字丢失了第一个字母?我不知道,但我的第一步是弄清楚忽略
到底做了什么,顺便说一句,最好不要尝试插入-5
名字。我试着把它放在getline(cin,names[I])后面;但这就产生了一个问题,我把它放在上面,如果我尝试3个名字,名字就可以了,但最后两个失去了第一个字母哇,太感谢了!这让我更好地理解了cin.ignore是什么意思,我认为这是我的主要问题。如果我们使用我们还没有学过的东西,我的教授会给出分数,所以我不能使用限制,但没有限制效果很好!
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);
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>