我正在编写一个需要将用户输入读入字符串对象的程序。我使用了getline(cin,name),但是当它到达提示符时,我可以输入任何内容并按Enter键,但它只是转到下一行,光标将一直闪烁,提示获得更多输入。从本质上讲,输入的提示似乎永远不会结束,无论我输入多少个字符或输入多少次。我甚至不知道它是否真的将输入发送到字符串对象中。可能导致这种情况的原因是什么?
这是迄今为止的主要功能的全部内容(它不完整,switch-case最终将有6个选项,但它编译时没有错误)相关部分从switch case 1开始:
#include <string>
#include <array>
#include <iostream>
#include "stdlib.h"
#include "Bank.h" //My own class. There is also a Bank.cpp, but I won't include the code in these unless they're deemed relevant
using namespace std;
void displayAccountInfo(); //will retrieve info on bank object
void main()
{
int accsCreated = 0; //Keeps track of how many accounts have been created so far. Allows placement of pointer to new bank object at an empty array index.
int option = 0; //Stores the option chosen by the user. Used in switch-case. Also ends do-while loop when ==6.
Bank* accounts[10]; //Will hold pointers to each bank object created by user in sequential order. No more than 10 accounts will ever be created.
Bank* accpntr; //Will point to one of the Bank objects. Used to initialize a pointer to the object in the accounts[] array.
//begin Menu prompt
do
{
cout << "[1] Create Bank object with values for accountNumber, name, and balance." << endl;
cout << "[2] Create Bank object with no parameters." << endl;
cout << "[6] End program" << endl;
cin >> option;
//begin option branch:
switch (option)
{
case 1:
{
int num; //holds account number
string name; //will hold account name as string object for use in Bank constructor
double balance; //holds account balance
cout << endl << "Enter an account number: ";
cin >> num;
cout << endl << "Enter a name for the account: ";
cin.ignore(std::numeric_limits<std::streamsize>::max()); //clears cin's buffer so getline() does not get skipped
getline(cin,name);
cout << endl << "Enter the balance of the account: ";
cin >> balance;
cout << endl;
accpntr = new Bank(num, name, balance); //creates a new bank object with attributes and a reference to it
accounts[accsCreated] = accpntr; //adds pointer to new bank object to first empty spot in array
accsCreated++; //increments total of how many bank objects have been created/what index position of accounts[] to create the next one at
} break; //end case 1
case 2:
{
accpntr = new Bank(); //creates a new bank object with an accountNumber of 9999, an empty name attribute, and a balance value of zero.
accounts[accsCreated] = accpntr; //adds pointer to new bank object to first empty spot in array
accsCreated++; //increments total of how many bank objects have been created/what index position of accounts[] to create the next one at
} break; //end case 2
case 6:
{
cout << "Ending Program." << endl;
}
} //end switch-case block
}
while (option != 6); //end menu prompt when user chooses option 6.
//end menu block
} //end function main()
答案 0 :(得分:0)
使用交替的提示和输入,这会在输入中包含线条结构,您应该坚持使用面向行的输入并将所有内容作为一行读取,并使用在适当的时候从字符串转换数值的操作。
这应该比使用行分隔符更加强大。