我现在遇到的问题是,它不会根据用户输入打印出输入。示例:
在我要向日历中添加日程表的日期插入之后,我输入的任务是“ C ++”,但是程序中什么都没有中断。我希望它可以打印“ C ++”,我认为应该在此部分出现问题:
for (;;) {
cout << "You task: " << endl;
string sunday;
if (!getline(cin,sunday) || sunday.empty())break;
sunday_task.push_back(sunday);
for (int i = 0; i<sunday_task.size(); i++){ // This part does not work
cout << sunday_task[i] << endl; // This part does not work
}
我尝试了很多答案,但似乎没有用。
#include <iostream>
#include <windows.h>
#include <vector>
#include <time.h>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
string login() {
start:
cout << "Please login to access your account" << endl;
cout << "Please enter your username or email: " ;
string username;
getline (cin,username);
if (username == "duxton"){
cout << "Please enter your password:";
string password;
getline (cin, password);
if (password == "password") {
cout << "You have successfully login" << endl;
char choice;
cout << "\n\nChoose one of the choice below:\n"
<< "a. Add a schedule to your calender\n"
<< "b. View your schedule for the month\n"
<< "c. Exit\n\n";
//Get the choice
cout << "Insert Option:";
cin >> choice;
// potential to be use in struct
vector <string> sunday_task ;
string days;
switch (choice)
{
case 'a': cout <<"Sunday Monday Tuesday Wednesday Thursday Friday Saturday" << endl;
cout << "Which day would you like to insert task to? " << endl;
cout << "Insert day : " ;
cin >> days;
if (days == "Sunday" or "sunday")
{
for (;;) {
cout << "You task: " << endl;
string sunday;
if (!getline(cin,sunday) || sunday.empty())break;
sunday_task.push_back(sunday);
for (int i = 0; i<sunday_task.size(); i++){
cout << sunday_task[i] << endl;
}
}
}
break;
case 'b': cout << "View calender" << endl;
break;
case 'c': break;
default:
cout << "Input Error!";
}
}
else {
cout << "Login failed" << endl; goto start;
}
}
else { cout << "Login failed" << endl; goto start;}
cin.get();
}
int main(){
login();
return 0;
}
我的输出是:
Please login to access your account
Please enter your username or email: duxton
Please enter your password: password
You have successfully login
Choose one of the choice below:
a. Add a schedule to your calender
b. View your schedule for the month
c. Exit
Insert Option:a
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Which day would you like to insert task to?
Insert day : sunday
You task: c++
^^在这部分之后,我希望它能打印出“ C ++”
对不起,因为我是StackOverflow的新手,我希望我已经清楚地说明了这一点,并提供了足够的信息。
答案 0 :(得分:1)
不相关的问题:string login()
就像我在相邻评论中提到的那样,如果您承诺一个字符串,则必须返回一个,否则会发生不好的情况。或将功能更改为void。始终在启用警告的情况下进行编译,请尝试对其进行修复。
您的问题是
cin >> string_variable
和cin >> char_variable
在cin
中留下未处理的换行符,因此,下次执行getline时,将得到一个空字符串。
在string temp; getline(cin, temp);
之后和cin >> choice;
之后放置cin >> days;
之类的东西,以吃掉多余的换行符。