2016-09-16 843 views
-5

我正在研究一个程序,但现在我遇到了一个问题,问题是我想输入两个数字,但光标在同一行。每当我输入任何数字,然后按Enter键移动到下一行,但我希望它在同一行。如何在同一行中输入多个输入?如何在C++的同一行中输入多个输入?

+0

控制台/终端不能这样工作。你可以使用GNU readline()或NCurses来解决它。或者你可以把你的I/O放在一个GUI中。你可能已经被低估了,因为这是一个常见的问题,正确的答案几乎总是“不这样做”。 –

回答

1

您可以简单地通过级联运算符cin。如果以这种方式编写代码:

int a,b; 
cout << "Enter value of a" << endl; 
cin >> a; 
cout << "Enter value of b" << endl; 
cin >> b; 

那么程序的执行将是这样的:

Enter value of a 
10 
Enter value of b 
20 

但要做到这在单行线,你可以这样写代码:

cout << "Enter the values of a and b" << endl; 
cin >> a >> b; //cascading the cin operator 

程序执行现在去从而:

Enter the values of a and b 
10 20 

如果以这种方式输入两个值(用空格分隔它们),则它按照您希望的方式工作 - 处于同一行中。
此外,在第一个片段中,如果您删除endl声明,您也可以将它全部在一行中,但我不认为这就是您想要的。

另请参阅:CASCADING OF I/O OPERATORS | easyprograming

+1

我建议使用''n''而不是'std :: endl',因为你不需要在这里刷新,因为'std :: cout'和'std :: cin'在内部耦合。 –

+0

@JanNilsFerner当然。 – progyammer

0

对于两个可变ab,你可以这样写代码,

cout << "Enter the values of a and b: "; 
cin >> a >> b; 

程序将被执行如下,

Enter the values of a and b: 5 10 
0
cout << "Enter the values of a and b" << endl; 
cin >> a >> b; 

计划将在此执行格式现在

Enter the values of a and b 
10 20