std::cin 将不起作用

std::cin Will not work

本文关键字:不起作用 cin std      更新时间:2023-10-16

我正在尝试使用std::cin >>但Visual Studio 2017说:

"二进制'>>':未找到采用类型为'std::istream'的左操作数的运算符(或者没有可接受的转换)">

完整代码:

#include "stdafx.h"
#include <iostream>
void verb()
{
std::cin >> "Enter a verb";
}

int main()
{
std::cout << "help";
return 0;
}

("help"是暂时的,直到我能void verb();工作。

使用std::cin读取输入

std::cin用于输入,您必须将要读取的值存储到变量中。

例如

std::string word;
std::cin >> word;

std::cin >> word;将分配给word用户输入的单词。因此,将字符串文字(例如"hello")传递给std::cin是没有意义的,因为它不知道如何处理它。

如果要向用户显示消息以告诉他们输入某些内容,只需像打印其他消息一样使用std::cout即可。

关于std::cin的其他有趣事情

您也可以使用一些其他类型,例如intfloat或其他类型直接与std::cin一起使用。

请注意,当输入带有std::cin的字符串时,它只会读取一个单词(用空格分隔),这意味着如果用户输入hello worldword的值将被hello- 如果你再次std::cin >> word;,你会得到world。要从std::cin中读取整行,请参阅此线程。

如果你想一次读取多个内容(以避免在代码中多次std::cin >>),你可以"链接"输入:

std::string word1, word2;
int number;
std::cin >> word1 >> number >> word2;

这将按预期工作,例如firstword 443351 lastword

你必须把它写在一个变量中

#include "stdafx.h"
#include <iostream>
#include <string>
std::string variable_a;
void verb()
{
std::cin >> variable_a;
}

int main()
{
std::cout << "help";
return 0;
}
#include <iostream> // Include input/output stream objects
#include <string> // Include string data type
using namespace std; // Use standard namespace library
int main()
{
string verb; // Declare verb as type string
cout << "Enter a verb: "; // Asks the user to enter a verb
cin >> verb; // Takes input as variable verb
system("pause"); // Pauses console
return 0; // Return value from function
}

此外,在将来创建程序时请尝试此操作。

  1. 删除">#include"stdafx.h">并复制原始代码。
  2. 启动 Visual Studio 2017。
  3. 在显示">新建项目"的位置下,选择项目类型。
  4. 当您进入">Win32应用程序向导"时,单击">下一步",然后在">其他选项"下,单击">空项目"。
  5. 您现在将看到一个空白屏幕。
  6. 在">项目"菜单选项卡下,单击">添加新项">(或控制 + Shift + A)
  7. 将现有代码复制到此项目中。

这应该可以解决问题