更好地了解getline()和cin [英] better understanding of getline() and cin
问题描述
尝试对控制台功能有一些基本的了解。我遇到问题,请考虑以下...
Trying to get some basic understanding of console functionalities. I am having issues so consider the following...
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
getline(cin, value);
MultiplicationTable(value);
getchar();
return 0;
}
我实际上是基于 http://www.cplusplus.com/doc/tutorial/basic_io/ 。我的IDE不识别getline()当然,当我编译应用程序。我收到错误
I actually based this off code from http://www.cplusplus.com/doc/tutorial/basic_io/ . My IDE is not recognizing getline() so of course when I compile the application. I get an error
'getline': identifier not found
现在看看这段代码
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
/*
This is a template Project
*/
void MultiplicationTable(int x);
int main()
{
int value = 0;
printf("Please enter any number \n\n");
cin>>value;
MultiplicationTable(value);
getchar();
return 0;
}
当我执行这行代码时,控制台窗口打开并立即关闭。我想我缺少一些关于cin。我知道它定界空间,但我不知道还有什么。我应该使用什么输入,使我的生活更轻松。
When I execute this line of code the console window opens and immediately closes. I think I a missing something about cin. I do know that it delimits spaces but I don't know what else. what should I use for input to make my life easier.
推荐答案
函数 getline()
在字符串头中声明。因此,您必须添加 #include< string>
。
它定义为 istream& getline(istream& is,string& str);
,但是用 int
而不是字符串对象来调用它。
The function getline()
is declared in the string header. So, you have to add #include <string>
.
It is defined as istream& getline ( istream& is, string& str );
, but you call it with an int
instead of a string object.
关于您的第二个问题:
当我执行这行代码时,控制台窗口打开,关闭
When I execute this line of code the console window opens and immediately closes
可能还有一个'\\\
字符输入到流中,当你的程序到达函数
' getchar()
(我假设你放在那里,所以你的窗口不关闭)。你必须刷新你的流。一个简单的解决方法是,而不是 getchar()
,添加行
There is probably still a '\n'
character from your input in the stream, when your program reaches the function getchar()
(which I assume you put there so your window doesn't close). You have to flush your stream. An easy fix is, instead of getchar()
, add the line
int c;
while((c = getchar()) != '\n'){}
这会清除您的讯息串,直到下一个换行符。
This will flush your stream until the next line-break.
注意: conio.h
的c ++标准和过时。
Remark: conio.h
is not part of the c++ standard and obsolete.
这篇关于更好地了解getline()和cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!