【发布时间】:2020-06-03 06:51:57
【问题描述】:
我编写了这个简单的程序来或多或少地“热身”使用 C++,当要求输入字符串时,程序停止按预期工作。
这里要求一个 int,它按预期工作:
#include <iostream>
using namespace std;
int main() {
cout << "enter something\n";
int usertypestuff;
cin >> usertypestuff;
cout << usertypestuff << " is a number.";
}
输出如下:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
enter something
12.5
12 is a number.
PS C:\Users\fortm\Documents\CPPPrac\MainPrac>
但是,当更改代码以改用字符串时,程序会跳过“输入内容”和 cin 行并跳转到新行(用于命令等)。
非工作代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "enter something\n";
string usertypestuff;
cin >> usertypestuff;
cout << usertypestuff << " is a number.";
}
输出日志:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> 12
12
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> hu
hu : The term 'hu' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ hu
+ ~~
+ CategoryInfo : ObjectNotFound: (hu:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\fortm\Documents\CPPPrac\MainPrac>
我已尝试使用 MinGW 和 CygWin 进行编译,但无济于事,我正在 Visual Studio 代码中使用 coderunner(在终端中运行已检查)运行程序。
【问题讨论】:
-
如果您不介意,能否请您重新表述一下您想做什么?我很难理解。
-
请显示无效的代码(minimal reproducible example),您能解释一下
causes the program to instead look for a command instead of running the program的含义吗? -
std::cin在遇到空格后停止接受输入。您应该确保您的字符串在开头没有任何空格。要使用空格输入,请使用std::getline (std::cin,usertypestuff) -
您是否尝试输入多行字符串?如前所述,
>>运算符将在任何空白处停止读取,包括换行符。当您按下Enter键时,程序将读取该行并(对于>>)从该行获取第一个“单词”。然后程序将打印其输出并退出,留下您可能输入的任何其他行作为控制台或 shell 的输入。如果您想读取单行,则使用单个std::getline调用(再次提及),否则在循环中使用std::getline来读取所有行。 -
顺便请edit把你的问题告诉我们你是如何运行程序的。