gpt4 book ai didi

c++ - 更好地理解 getline() 和 cin

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:58 25 4
gpt4 key购买 nike

尝试对控制台功能有一些基本的了解。我有问题,所以请考虑以下...

#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(),所以当然在我编译应用程序时。我得到一个错误

'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 的东西。我确实知道它分隔了空格,但我不知道还有什么。我应该使用什么输入来让我的生活更轻松。

最佳答案

函数getline()在字符串头中声明。所以,你必须添加 #include <string> .它被定义为 istream& getline ( istream& is, string& str ); , 但你用 int 来调用它而不是字符串对象。

关于你的第二个问题:

When I execute this line of code the console window opens and immediately closes

可能还有一个'\n'当您的程序到达函数 getchar() 时,您在流中输入的字符(我假设你把它放在那里所以你的 window 不会关闭)。你必须冲洗你的流。一个简单的解决方法是,而不是 getchar() , 添加行

 int c;
while((c = getchar()) != '\n'){}

这将刷新您的流,直到下一个换行符。

备注:conio.h不是 c++ 标准的一部分并且已过时。

关于c++ - 更好地理解 getline() 和 cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2915049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com