How to read input into the array of strings where no string is longer than 4 characters?

147 views Asked by At

How would one go ahead and write parts of a string inside a for-loop? Let's say I have this code:

string str[64];
for( int i = 0; i < 64; i = i + 4 )
{
    cin >> str[i];
}

Everytime it enters the loop, I want to write four elements of the string. How would I go ahead and to that, since the code I wrote does not work? :P

Thanks :)

2

There are 2 answers

5
haccks On

Try this

for( int i = 0; i < 64; i = i + 4 )
{
     for( int j = i; j < i + 4; j++ )
        cin >> str[j];
}  
1
LihO On

Note that:

std::string str[64];

declares an array of 64 std::string objects. If you'd like to read from the standard input character by character and fill this array with strings of maximum length 4, then it could look like this:

char c;
for (int i = 0, j = 0; std::cin >> c && i < 64; ++j) {
    str[i].push_back(c);
    if (j == 3) {
        i++;
        j = 0;
    }
}

However also consider to do the opposite thing:

  1. read "long" string at once (if your input is within a single line, use std::getline)
  2. use std::string::substr to tokenize this string into small strings of length 4
    • and if you need to hold these tokens in memory, use std::vector instead of an array

i.e. :

std::string line;
if (std::getline(std::cin, line))
{
    size_t lineLen = line.length();
    std::vector<std::string> tokens;

    for (int i = 0; i < lineLen; i = i + 4)
        tokens.push_back(line.substr(i,4));

    for (size_t i = 0; i < tokens.size(); ++i)
        std::cout << tokens[i] << ", ";
}

You might also consider calling tokens.reserve(len/4 + 1); after the tokens vector is constructed to prevent redundant memory reallocations. And don't forget to #include <vector>.