当我运行下面的代码,并提示输入 高尔夫结构时插入一个新行(按Enter键),第二次调用该函数不会请求输入并完成,如果我再次输入。我读过:cin.get(),cin.clear(),cin.ignore(...),但似乎没有任何帮助。cin.get()问题与空行
我敢肯定,它与多个.cpp文件和标题无关,但我把代码原样。
我正在使用Visual Studio C++ 2010 - Express。
在此先感谢您的帮助!
头文件:golf.h
#ifndef GOLF_H
#define GOLF_H
const int Len = 40;
struct golf{
char fullname[Len];
int handicap;
};
int setgolf(golf & g);
void showgolf(const golf & g);
#endif
golf.cpp
#include "stdafx.h"
#include "golf.h"
#include <iostream>
#include <string>
using namespace std;
int setgolf(golf & g){
cout << "Enter a name for the golf structure:" << endl;
if (cin.get(g.fullname,Len)) {
cin.get(); // deals with the '\n' incase the user inputs a valid string
return 1;
}
else{
return 0;
}
}
void showgolf(const golf & g){
cout << "this golf structure contains the following information:" << endl;
cout << "name: " << g.fullname << endl ;
cout << "handicap: " << g.handicap << endl ;
}
的main()
#include "stdafx.h"
#include "golf.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
golf myGolf;
// check of int setgolf(golf & g);
int answ = setgolf(myGolf); //try to input empty string
showgolf(myGolf);
cout << "the number returned :" << answ << endl ;
answ = setgolf(myGolf); // normal string
showgolf(myGolf);
cout << "the number returned :" << answ << endl ;
return 0;
}
您可能会考虑使用自由函数['std :: getline()'](http://en.cppreference.com/w/cpp/string/basic_string/getline)。 – WhozCraig 2013-02-18 19:25:32
我认为cin.get()不会消耗当你输入时产生的换行符。所以无论何时再次调用它,它都会在那里消耗,不会输入任何内容。如果您想快速回答,请调用cin.get()两次以获取单个输入。 – mostruash 2013-02-18 19:35:21
mostruash - >已经尝试了几次。没有运气。 WhozCraig - >我试图熟悉cin.get()。 ***忘了发起myGolf,myGolf = {“某个名字”,6};但在这里无关 – Stasv 2013-02-18 19:38:23