How to Take Input String Till End of Line in C++ Without the Use of Getline

How to Take Input String till End Of Line in C++ without the Use of getline

cin >> value;, like all formatted input functions, skips all whitespace while looking for the next character to read. Whitespace includes '\n', so it will never be read.

To read all characters, including the whitespace, you can use an unformatted input function like cin.get(value) instead.

C++ - Reading a line without getline [duplicate]

To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class.

Note that std::getline and std::istream::getline are two separate functions. The former will work with std::string while the latter will work with C-style strings (i.e. sequences of characters that are terminated by a null character).

Therefore, if you are not allowed to use std::string, then you can still use std::istream::getline, for example like this:

char line[200];
String street;

std::cout << "Street: ";

if ( std::cin.getline( line, sizeof line ) )
{
//the array "line" now contains the input, and can be assigned
//to the custom String class
street = line;
}
else
{
//handle the error
}

This code assumes that your custom class String has defined the copy assignment operator for C-style strings.

If it is possible that the lines will be larger than a fixed number of characters and you want to support such lines, then you could also call std::istream::getline in a loop:

char line[200];
String street;

std::cout << "Street: ";

for (;;)
{
std::cin.getline( line, sizeof line );

street += line;

if ( std::cin.bad() )
{
//TODO: handle error and break loop, for example by
//throwing an exception
}

if ( !std::cin.fail() || std::cin.eof() )
break;

std::cin.clear();
}

This code assumes that operator += is defined for class String.

This loop will continue forever until

  1. getline succeeds (i.e. it is able to extract (but not store) the newline character), or

  2. end-of-file is reached (eofbit is set), or

  3. an error occurs (badbit is set).

How to store input as a string until one or more specific string(s) has/have been entered in C++?

I came up with the following solution:

#include <iostream>
#include <vector>
using namespace std;

#define MAX_TARGET_LENGTH 500

int main() {
char target[MAX_TARGET_LENGTH];
while(true)
{
cout << "Enter source string: ";
while(true)
{
cin.getline (target, MAX_TARGET_LENGTH);
std::string line = target;
if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}
}
}
return 0;
}

I am using the String class to solve the problem.

Strings are objects that represent sequences of characters.

and they come with useful features. One of those is the function "compare". With it you can check if a string is equal to another string. The function will return 0, if the strings are identical. Otherwise it will return 1 or -1 (more information here).

The main thing going down in in the inner while loop.

while(true)

lets the while loop continuing forever.

You get a new line of input with

    cin.getline (target, MAX_TARGET_LENGTH);

which you store in the variable target. You can then turn "target" into a string with

std::string line = target;

because, the types are compatible. The if-statement then checks the input for "end" or "END".

if(line.compare("end") == 0 || line.compare("END") == 0)
{
break;
}

If one or both of those statements are true, "break" exits the inner while loop and makes the program print "Enter source string: " again.

Reading string by char till end of line C/C++ [duplicate]

You want to use single quotes:

if(c=='\0')

Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.

However, the end-of-line is represented by the newline character, which is '\n'.

Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.

getline(cin, aString) receiving input without another enter

When you mix standard stream extraction with getline, you will sometimes have getline return the empty string. The reason for this is that if you read input with >>, the newline character entered by the user to signal that they're done is not removed from the input stream. Consequently, when you call getline, the function will read the leftover newline character and hand back the empty string.

To fix this, either consistently use getline for your input, or use the ws stream manipulator to extract extra white space after a read:

cin >> value >> ws;

This will eat up the newline, fixing the problem.

Hope this helps!

How to read from input until newline is found using scanf()?

scanf (and cousins) have one slightly strange characteristic: white space in (most placed in) the format string matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.

This means the trailing '\n' is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.

One way to deal with that is something like this:

scanf("%2000s %2000[^\n]%c", a, b, c);

if (c=='\n')
// we read the whole line
else
// the rest of the line was more than 2000 characters long. `c` contains a
// character from the input, and there's potentially more after that as well.

Depending on the situation, you might also want to check the return value from scanf, which tells you the number of conversions that were successful. In this case, you'd be looking for 3 to indicate that all the conversions were successful.

Problem with removing the \n from a string read in with getline()

What you need is simply to put a \0 where the \n is.

It could look like this;

char *line = NULL;
size_t length = 0;
ssize_t chars_read;
// ...

if(chars_read > 0 && line[chars_read-1] == '\n') {
line[chars_read-1] = '\0';
// special care for windows line endings:
if(chars_read > 1 && line[char_read-2] == '\r') line[chars_read-2] = '\0';
}

Reading till the end of a line in C++

Split your input stream into lines

std::string line;
while (std::getline(input, line))
{
// process each line here
}

To split a line into words, use a stringstream:

std::istringstream linestream(line); // #include <sstream>
std::string word;
while (linestream >> word)
{
// process word
}

You can repeat this for each word to decide whether it contains a number. Since you didn't specify whether your numbers are integer or non-integers, I assume int:

std::istringstream wordstream(word);
int number;
if (wordstream >> number)
{
// process the number (count, store or whatever)
}

Disclaimer: This approach is not perfect. It will detect "numbers" at the beginning of words like 123abc, it will also allow an input format like string 123 string. Also this approach is not very efficient.

c++ getline() doesn't seem to operate correctly, Doesn't read the line till the end

It looks like you've tried all kinds of things to make this work, including reading from cin in the middle of your loop that reads from file.. Very strange. I suggest you throw out the entire loop and try something simple as follows:

You just read one line at a time. For each line you read, you put that into a string stream and read the values out of that. To keep it even simpler, just read a string for everything, even if it's supposed to be just one character.

// Note: requires <sstream>

string line;
while(getline(file, line))
{
istringstream iss(line);
string cls, name, surname;
if (iss >> cls >> name >> surname)
{
cout << name << " " << surname << " class: " << cls << endl;
}
}

This does assume that there are always exactly two names, and it seems like that might not be the case for your input.

As an alternative, you could try reading the single character, then ignoring whitespace, and then read the entire rest of line:

char cls;
string fullname;
while (getline(file >> cls >> std::ws, fullname))
{
cout << fullname << " class: " << cls << endl;
}

Note that the above is being a bit lazy, and as a result this might break if you encounter an empty line in your file. So, combining with the istringstream approach would be the way to go:

string line;
while (getline(file, line))
{
istringstream iss(line);
char cls;
string fullname;
if (iss >> cls >> std::ws >> fullname)
{
// Note you may also want to test cls is valid (e.g. isalpha(cls))
cout << fullname << " class: " << cls << endl;
}
}

In the end, if your input is line-based, then as a general preference you should read lines and then decide what to actually do with them.



Related Topics



Leave a reply



Submit