我一直试图进入C++,但我甚至无法获得最简单的编程来为我工作。C++字符串在多行上打印
while(true) {
cout << "."
string in;
cin >> in;
cout << "!" << in
}
我希望得到:
.1
!1
.1 2
!1 2
我实际上得到:
.1
!1
.1 2
!1.2
我一直试图进入C++,但我甚至无法获得最简单的编程来为我工作。C++字符串在多行上打印
while(true) {
cout << "."
string in;
cin >> in;
cout << "!" << in
}
我希望得到:
.1
!1
.1 2
!1 2
我实际上得到:
.1
!1
.1 2
!1.2
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] >
正是我以后。谢谢! –
如果你想读整行,然后格式化输入直接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';
}
}
虽然这不是真正的代码,这是很明显的你的意思是前两个'cout'语句是外循环。做到这一点,并改变'cout << ">“<< cmd;'到'cout << ">”<< cmd <<'\ n';'你就完成了。 –
@VaibhavBajaj完美。谢谢。我会尽量让它适应以后的工作。 :) –