how do i assign the string input of a user to a char? cin>> only gets the part before the first space; for instance, say a user inputs "This is a test." i'd like ot assign that to a char
how do i assign the string input of a user to a char? cin>> only gets the part before the first space; for instance, say a user inputs "This is a test." i'd like ot assign that to a char
use cin.getline
user inputs "this is a test"
char uinput[10];
cin.getline(uinput,10,"/n")
// uinput is the string name, 10 is the maximum characters it will bring in, "/n" tells it to stop at the new line character. That will read in the input from the user.
Or you can do while loop and read characters using getch (conio.h library). This function returns one character each time user presses a key. Terminate the loop when this character equals to 13 (this indicates user pressed Enter key). This is more complicated, but gives you control over the process and you can specify how to display characters user writes (or even if to display).
Please excuse my poor english...
when i try to use getline, the program does not give me a chance to enter a string... ?
This will input 9 characters, reserving the tenth space for "/0", the null terminating character.Originally posted by curtner
use cin.getline
user inputs "this is a test"
char uinput[10];
cin.getline(uinput,10,"/n")
// uinput is the string name, 10 is the maximum characters it will bring in,
Try this: It works fine.
Code:#include <conio.h> #include <iostream> using namespace std; int main() { const int limit = 255; //or whatever char *text = (char*)malloc(limit); int i = 0; for (char input = getch(); 13 != input; i++, input = getch()) { text[i] = input; cout << input; } text[i] = '\0'; //add terminator to the end return 0; }You can't assign string to a char. You can assign string to array of chars - that's what my code does. More complicated version of my code would allocate text array dynamically, but you probably don't need this. The easiest thing is to use <string> library. It gives you string datatype which simplifies string operations as much as possible.for instance, say a user inputs "This is a test." i'd like ot assign that to a char
Please excuse my poor english...
This is because you are calling it after a cin>> operation. The previous cin>> left a newline char in the stream buffer and getline encountered that and thought that input was over. After calling cin>> but before the cin.getline() add this line :-when i try to use getline, the program does not give me a chance to enter a string... ?
cin.ignore(80,'\n');
This will get rid of the newline from the buffer and allow getline to function normally.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
thanks alot