Im SOO stuck. Writing a program to read a txt file and output the contents according to the linelength. I'm having problems with reading the spaces and \n characters. If there is more than one ' ' then the program correctly counts and outputs it however if there is only 1 it fails to identify it and skips its output. There is also irregular output of \n characters. Can anyone help?
while (!ins.eof())
{
if (ins.peek() == '\n') // if newline character
{
cout << '\n';
ins.ignore(1, '\n'); // move input forward
n = 0;
total = 0;
}
elseif (ins.peek() == ' ') // if space count spaces
{
while (ins.peek() == ' ') // counts number of spaces and stores in n
{
n++;
ins.ignore(1, ' '); // move input forward
}
}
else // else we are looking at a word
{
string s;
ins >> s; // input word
if (n + total + static_cast<int>(s.length()) > linelength) // if spaces plus word plus total amount > line length
{
cout << '\n'; // got to new line
cout << s; // output s
total = s.length(); // reset total to length of s
n = 0; // resets space counter
total2 += total;
}
else // other wise
{
for (int p = 0; p < n; p++) // output spaces
cout << '_';
cout << s; // output the word
total += n + static_cast<int>(s.length()); // increase total
n = 0; // resets the space counter
total2 += total;
}
}
}
Its an assignment. I have a preset txt file and have to design a program in which a user is able to enter a number for the linelength. I am going to pass that as the argument for this procedure. I'm not allowed to do it by storing the txt.file line by line... This is why i am trying to use the peek() functions but i may be going down the wrong path. It correctly prints spaces when there is more than 1 ie. "red__car" using underscores for clarity. However when there is just 1, the peek() function just returns the next char after the space and the program executes the final else. So when the input is "James Smith" the peek() function returns the ascii for S and thus the final else is executed but when the input is "James Smith" (2 spaces) the peek() function returns ascii for " " (32) so the else if is executed (this strangely correctly counts 2 spaces).
I'm trying to figure out whether this is to do with the input position after the input of a word.
after line 23 the future input should be the char directly after the word just inputted right?