Using "getchar()" help! HELP HELP HELP

Okay. I am VERY new at c++, and have just learned in class about arrays and strings.

This is the problem.

I am asked to get a word from the user, and output the length of it.

The part I am having trouble with is the input. This is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
	char user_input[100];
	int x = 0;
	
	cout << "== String Length ==" << endl;
	cout << "Enter a word:" << endl;
	
	for(char new_char = getchar(); new_char != '\n'; new_char = getchar())
	{
		user_input[x] = new_char;
		x++;
	}  //this is how I was told to get input.
	
	cout << user_input << endl;
	
}


but when the user inputs anything less than four characters, it outputs the first few and then gibberish. Can someone tell me why this is happening? In REALLY SIMPLE words?
Last edited on
//this is how I was told to get input.

Well, the first thing I was going to comment on is getline will get a word for you no problem. Also, it's a really weird loop. I did a double take before I understood what was going on.

This would be more understandable, I find:

1
2
3
4
5
6
7
8
9
10
11
char new_char;

do
{
     new_char = getchar();

     if(new_char != '\n')
     {
          user_input[x++] = new_char;
     }
} while(new_char != '\n');


OK, now on to the real problem.

but when the user inputs anything less than four characters, it outputs the first few and then gibberish.

When I ran it there was gibberish even if I put four or more characters. The gibberish is there because when cout prints a char array or char*, it keeps printing until it sees the null terminator character '\0' (ASCII 0). This tells it when the printing is finished.

After the loop, you should put user_input[x] = '\0'; and then there will be no garbage printed out. This of course assumes that x <= 99 upon termination of the loop.
Last edited on
Why don't you use the string class? Is there a requirement that say's you must use getchar()?

You can store string data, and there is a method that returns the number of characters contained within that string, without the fuss of null characters and so on (and it will look prettier).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//code omitted
#include <string>

using std::string;

int main()
{
    string myString;
    
    cin>>myString;
    cout<<"my string is: " <<myString.length() <<" characters in length!" <<endl;

    //code omitted
}


The documentation you need is here: http://www.cplusplus.com/reference/string/string/

You can use this method to get the number of characters contained within the string: http://www.cplusplus.com/reference/string/string/length/

I hope this helps!
Last edited on
Topic archived. No new replies allowed.