String Function Lengths

Hey guys,
I encountered a problem with my codes.
I am trying to...

1. Receive the entire user input, including spaces and blanks, for example if the input was "Hello World" if I use a cin >> I will only get "Hello"
I'm trying to figure out how to get the entire thing

2. I am attempting on the int len = myString.length(); but I'm always getting a 0
what am I doing wrong?


string myString, junk;

cout << "insert string variable" << endl;
cin >> myString;
int numone = myString.length(); //length function

cout << myString; //seeing the user input

getline (cin, junk,'\n'); //this is where I am trying to erase
getline (cin, myString, '\n'); //the space between to get the entire
getline (cin,myString); //user input

cout << myString << endl; //testing
cout << junk << endl;
cout << numone; //testing for the length

thanks in advance!
Last edited on
You have to use cin.getline to get an array of characters from user input. This can by converted to a string, then the length function works as usual.

1
2
3
4
5
6
7
8
    char myArray[256];

    cout << "insert string variable" << endl;
    cin.getline (myArray, 256);
    string myString(myArray);
    int numone = myString.length(); //length function

    cout << myString << "\n" << numone; //seeing the user input 
Last edited on
Hey Brent,
thanks for the help!
I was wondering, what does the "256" do?
and does it have to be a char?
thanks again!
The "256" refers to the last array of the char.


Yes it has to be char for accuracy
I was wondering, what does the "256" do?
and does it have to be a char?


256 is the size of the array. The last addressable character in the array would be at index 255.

Doing it that way is kind of silly.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
    std::string input ;
    std::cout << "Enter a string:\n" ;
    std::getline(std::cin, input) ;

    std::cout << "You input \"" << input << "\" which has a length of " << input.length() << ".\n" ;
}


There is no need for an intermediary array.
thanks to the both of you!
I was able to get it! this is what I came up with

string input;

cout << "Enter a string" <<endl;
getline(cin,input);
cout << "your input is..." << input <<endl
<< "And the lenghth is: " << input.length() << endl;

thanks so much appreciate it!
Topic archived. No new replies allowed.