Pergunta

I am trying to input a few first names into a double character array with the following code:

int main(void) 

char firstName[4][10];
Int num = 2;

for (int i=0; i<num; i++) 
  for (int j=0; j<10; j++) 
        cin >> firstName[i] [j] ;
        if(firstName[i] [j] == '.') 
            break;

Return(0);

Basically, I am looking for a simple, better way of inputting the names into a double char array without having to end the input with a period. If I try using the char delimiter. ' /0' it still attempts to fill in the first full row of the characters array before continuing.

Foi útil?

Solução

On the coding side, since this is C++, don't store lists of strings in a two-dimensional array of char. Try std::vector<std::string> instead. And don't read your file one character at a time; read larger blocks of characters.

If you can guarantee that there are never spaces embedded within first names, you can write something like cin >> s;, where s is of type std::string, to read a whole name in one operation.

If you may have blanks within a name, try reading an entire line of the file into an std::string and extract the data you need from there. If that's too complicated, maybe you need to reconsider your input file's format. (Maybe include a sample of an input file next time so we can see what you thought you were trying to read.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top