这是我第一次使用stackoverflow。关于getline,我一直找不到需要的信息。我在一个简单的工程转学编程课上学习,所以我们编写的代码非常简单。我所要做的就是将用户定义的问题和答案放入两个不同的数组中。我的while循环看起来像这样(我之前用for循环,但转为while只是想看看它是否会停止崩溃):
int main ()
{
srand((unsigned)time(0));
string quest1[100], answ1[100];
int size1, x = 0, num, count1, visit[100], shuffle[100];
fstream flashcard1;
cout << "flashcard.cpp by NAME\n" << endl;
cout << "This program allows user to manipulate questions and answers for studying.\n" << endl;
cout << "\nHow many flash cards will be entered(MAX 100)? ";
cin >> size1;
cout << endl;
while(x < size1)
{
cout << "Enter Question: ";
getline(cin , quest1[x]);
cout << endl;
x = x++;
/*
cout << "Enter Answer: " << endl;
getline(cin,answ1[x]);
cout << endl;
flashcard1.open("flashcard1.dat", ios::app);
flashcard1 << quest1[x] << " " << answ1[x] << endl;
flashcard1.close();
cout << "Data Stored." << endl;
*/
}
}
我在调试时注意到了输入答案部分以及将数据保存到文件中的部分。当我运行程序时,它会跳过第一个问题的getline,显示“输入问题”的第二个循环,而其余的getline正常工作。所以如果我有一个大小为5的size1,程序只会填充数组位置1-4。请帮帮我。
这是一个简单的闪卡程序,它可以像创建闪卡一样进行学习并随机洗牌。
x = x++;
是未定义行为。正确的应该是x++
(或者++x
,x += 1
,x = x + 1
,x -= -1
等等)。 - Seth Carnegie'\n'
时使用endl
。std::cout << std::endl
等效于std::cout << '\n' << std::flush
。另外,永远不要使用"using namespace std;",即使(尤其是)你的书本或教授告诉你要这样做。导入整个std
命名空间可能会产生难以识别的错误。 - Robᵩusing namespace std;
的说法有些夸张了。只要你知道其中的危险,你可以在非常受控制的环境中使用它(例如单文件短程序)。 - Seth Carnegie