Problems with Partially Filled Char Array

I am trying to create a character array as a first step in a function that deletes repeated characters from the array. However, after I cin the first character, I get the bizarre output of ten upside-down question marks. Any ideas as what is going on here? Thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include <iostream>
#include <string>
using namespace std;
int main()
{
    char foo[10];
    int i, input, x;
    
    for(i = 0; i < 10; i++)
    {
        cin >> input;
        if (input != 'z')
        {
            foo[i] = input;
        }
        else
            break;
    }
    
    for(x = 0; x < i; x++)
    {
        cout << foo[i] << endl;
    }
    
    return 0;
}
You're trying to extract alphabetic input into an int which causes line 11 to fail and put std::cin into an error state so that input is never assigned any value and instead consists of the random junk occupying it's memory which you assign to the elements of the array?
I changed input to type char, and that allows me to input more than one character. However, the output is still upside-down question marks.
Last edited on
One of your other problems is you are referencing foo[i] in a for loop using x. This is why it's dangerous and wrong to take the initilizations for the for loop outside the scope of the for loop. Try fixing that and see what you get.
Topic archived. No new replies allowed.