[英]C++ String Prints on Multiple Lines
我一直在尝试使用C ++,但是我什至无法获得最简单的编程来为我工作。
while(true) {
cout << "."
string in;
cin >> in;
cout << "!" << in
}
我希望得到的是:
.1
!1
.1 2
!1 2
我实际得到的是:
.1
!1
.1 2
!1.2
如果您想阅读整行,那么直接在std::cin
上进行格式化的输入就std::cin
了。 使用std::getline
代替。
大致像这样:
#include <string>
#include <iostream>
int main() {
while(true) {
std::cout << "."
std::string in;
getline(std::cin, in);
std::cout << "!" << in << '\n';
}
}
cin是从标准输入读取的流,该输入可能无法以您期望的所有方式运行。 提取运算符>>
从cin读取,直到到达空格为止,因此cin >> cmd
仅将cmd设置为等于命令中的第一个单词。 其余单词仍在cin中,因此在程序打印后
> test
它再次循环,提示输入,并从cin读取test2
,而不是允许您向流中添加其他内容。
如果要阅读整行,请使用getline。
#include <string>
using std::string;
#include <iostream>
using std::cin; using std::cout; using std::getline;
int main() {
while (true) {
cout << "\n\n";
cout << "[CMD] > ";
string cmd;
// Store the next line, rather than the next word, in cmd
getline(cin, cmd);
cout << "> " << cmd;
}
}
这将按您期望的那样执行:
[CMD] > test
> test
[CMD] > test test2
> test test2
[CMD] >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.