E.Cross
E.Cross

Reputation: 2137

Concatenating character arrays in c++

I have been requested to read a file from standard in like:

./gscheck < testfile

Where gscheck is the name of my compiled executable. Anyways, I need to use the function cin.getline() to read each line into a character array. I know how to do this,

char line[250];
while (cin.getline(line, 250))
{
    Do stuff;
}

But ultimately, I do not want to do anything per line, I want to concatenate every line into one gigantic character array. How can I, using the above methods, create a larger character array that contains each line in order and includes the newline breaks, such that I am essentially 'slurping' from the file, and then parsing it character by character, but not using the string class.

Upvotes: 2

Views: 589

Answers (4)

JKor
JKor

Reputation: 3832

Based off of @KerrekSB's answer, you could use the deprecated std::ostrstream, which uses character arrays (actually a char *, but with strlen you can get it to work easily as an array).

std::ostrstream oss;
oss <<std::cin.rdbuf();
return oss.str();

Upvotes: 1

PiotrNycz
PiotrNycz

Reputation: 24347

Just in case you have limitation not to use dynamic memory, Which std::string is using for sure:

char a[VERY_BIG_SIZE_ENOUGH_FOR_FILE];
std::cin.read(a, VERY_BIG_SIZE_JUST_ENOUGH_FOR_FILE - 1);
a[VERY_BIG_SIZE_JUST_ENOUGH_FOR_FILE - 1] = '\0';

Upvotes: 1

epsalon
epsalon

Reputation: 2294

How about this then:

char file[2000];
char *end=file+1998;
char *ptr=file;
while (!cin.eof() && ptr < end) {
  cin.getline(ptr, end-ptr)
  ptr += strlen(ptr);
  *ptr++ = "\n";
  *ptr = 0;
}

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476970

Don't do it.

Just say no.

Don't use "character arrays".

Seriously.

Use std::string.

std::string result;

for (std::string line; std::getline(std::cin, line); )
{
    result += line;
}

But if you just want to read everything and not actually parse lines (and instead preserve newlines), it might be even simpler to access the input buffer directly:

std::ostringstream oss;
oss << std::cin.rdbuf();
return oss.str();

Upvotes: 0

Related Questions