问题
Suppose we have the following sentence: The last time I shopped was __ days ago.
How would I change this into C++ code, so that __ is an integer that the user inputs?
So far, I have come up with the following, which puts the first string, the integer input, and the second string on separate lines:
#include <iostream>
using namespace std;
int main(){
cout << "The last time I shopped was ";
int x;
cin >> x;
cout << "days ago";
}
I would like to get all of this onto the same line - how do I do this?
回答1:
You can't do that in standard C++11 (or C++14 or C++17), without any additional and system specific library.
You need a system specific library that handles an editable line (in the terminal where you are running your program). Standard streams in C++ don't have that (and standard C++ don't even know about terminals; in many cases, such as command pipelines, or redirections, or shell scripts running in batch or as a cron job, you might not have any).
This answer suggests something for Windows (but it probably is not robust since it doesn't handle all cases, such as programs running in batch or with redirections).
On Linux and POSIX systems, you would use something related to tty-s (see the tty demystified and termios(3)). You might use isatty(3) to detect if you've got a terminal. Then you could use a library such as ncurses or readline. BTW, these libraries might have been ported to Windows too (I leave you to check that).
Another approach might be to write some GUI application (showing a window where some parts are editable, perhaps as a GUI form). Then you'll need a GUI toolkit library like Qt.
Or you could make your program a web application. Then (assuming you know some web technologies and at the very least understand the HTTP protocol and HTML5) use some HTTP server library like Wt or libonion (and your user would use his web browser to interact with your application, which becomes some specialized web server)
PS. Whatever approach you choose, it is more complex than you might believe and would require at least several days of work (first, reading documentation to become familiar with the library you want to use).
来源:https://stackoverflow.com/questions/46762331/in-c-code-how-do-i-get-the-user-to-input-a-number-in-between-2-strings-of-tex