1
votes

fgetc() for proccessing entered chars - char by char. The function returns integer value of entered char.

I need to check these:

  • Each town shouldn't exceed 30 characters
  • There exists a "-"(dash) character on each line (splitting the whole line to two cities)

I've defined 31-int-array and one integer for counting chars. When user enter "-", i need to save the chars as a string to another array (actually map).

printf("Enter route (city - city):\n");

char town[31];
int character, charsOnRow = 0, i = 0;
map<int, string> route;

while (!feof(stdin)) {
    character = fgetc(stdin);
    if (character != '-' && character != '\n') {
        if (charsOnRow < 30) {
            town[charsOnRow] = character;
            charsOnRow++;
        } else {
            printf("Invalid input.\n");
        }
    } else if (route.size() == 0 && character == '\n') {
        printf("Invalid input.\n");
    } else {
        town[charsOnRow] = '\0';
        route[i] = town;
        charsOnRow = 0;
    }
}

So example of input would be this:

Syracuse - Utica
Binghamton - Syracuse
Binghamton - Utica

How should i fix it and be able to save int-array to map<int, string>?

3
you have declared an array of char pointers. I don't think that's what you want - ThomasMcLeod

3 Answers

2
votes

You have both technical errors (invalid C++) and logic errors.

A main cause of that is complexity of doing char-by-char input.

You may find it easier to use C++ level i/o: declare a std::string variable to hold a complete line of input, read it by using std::getline.

Cheers & hth.,

0
votes

You need to declare town as a character array. Currently you have it as a array of character pointer.

Change

char * town[31];

to

char town[31];
0
votes

Actually fgetc return an int to indicate error condition, if the value is < 0, you had an error, otherwise, you can simple add it to a string, like:

std::string str;
for(;;)
{
  int ch = fgetc(fp);
  if(ch < 0)
    throw error();

  str += ch;
}

When you fill up the string, just add it to the map: map[yourIntValue] = str;

Also, on your code: char * town[31];

This is a array of pointer, the correct for your case is: char town[31];

And to add it to the map, you can simple use: map[yourIntValue] = std::string(town);