C++程序在使用int与cin时可以工作,但不能使用字符串。

问题描述 投票:0回答:2

我写了这个简单的程序来 "热身 "使用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> 

然而,当把代码改为使用字符串时,程序跳过 "enter something "和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运行程序(在终端运行被选中)。

c++ string cin
2个回答
0
投票

当我这样做的时候,它工作得很好。

程序代码

#include <iostream>
#include<string>
using namespace std;

int main() {
    cout << "enter something\n";
    string usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
    return 0;
}

输出:

enter something
25
25 is a number.

0
投票

你可以使用 std::to_string() 函数来转换 用户类型 到字符串。

string str = to_string(usertypestuff);

0
投票
cin >> usertypestuff;

std::operator>>(std::istream&, std::string&) 方法从流中读取,直到找到一个空格,然后返回。 然后程序的其余部分就会运行。 你的代码很好,但我怀疑在终端运行程序时,你输入了一个中间有空格的输入。 程序读到空格,然后完成正确运行,然后退出。之后,终端会把输入的其余部分读作下一个要运行的程序。但由于你的输入不是一个有效的命令,终端会显示一个 CommandNotFoundException.

© www.soinside.com 2019 - 2024. All rights reserved.