Reading a Full Line of Input

Reading a full line of input

is there a way like readLines till CTRL+Z is pressed or something ??

Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):

string line;

while (getline(cin, line)) {
// do something with the line
}

This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin signals an error.

How to read whole line input in Java without skipping it (scanner.next())

Your code skips user input because nextLine() method reads a line up-to the newLine character (carriage return). So after nextLine() finishes the reading the carriage return actually stays in the input buffer. That's why when you call sc.next(), it immediately reads the carriage return from the input buffer and terminates the reading operation. What you need to do is implicitly clear the input buffer after a read-line operation. To do that, simply call sc.next() one time after line 16.

    System.out.print("What's the name of your parking ? ");
String parkName = sc.nextLine();
sc.next();
System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");

C++ reading input from cin until the whole line has been read

Now that you clarified your question it's way clearer. And @TeoZec answer should be right. I just wanna note two things that seem buggy in your above code:

else if (c == '-')
{
num.push(a+b);
count--;
}

here you probably wanted a-b instead.

if (count>1)
{
b = num.top();
a = num.top();
num.pop();
num.pop();

b and a will be the same number here, you should call pop() before getting the second number, like:

if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();

Reading lines from input

You could use std::from_chars (and reserve() the approximate amount of lines you have in the file, if you store the values in a vector for example). I also suggest adding support for reading directly from the file. Reading from a file opened by the program is (at least for me) faster than reading from std::cin (even with sync_with_stdio(false)).

Example:

#include <algorithm> // std::for_each
#include <cctype> // std::isspace
#include <charconv> // std::from_chars
#include <cstdio> // std::perror
#include <fstream>
#include <iostream>
#include <iterator> // std::istream_iterator
#include <limits> // std::numeric_limits

struct foo {
int a[3];
std::string s;
};

std::istream& operator>>(std::istream& is, foo& f) {
if(std::getline(is, f.s)) {
std::from_chars_result fcr{f.s.data(), {}};
const char* end = f.s.data() + f.s.size();

// extract the numbers
for(unsigned i = 0; i < 3 && fcr.ptr < end; ++i) {
fcr = std::from_chars(fcr.ptr, end, f.a[i]);
if(fcr.ec != std::errc{}) {
is.setstate(std::ios::failbit);
return is;
}
// find next non-whitespace
do ++fcr.ptr;
while(fcr.ptr < end &&
std::isspace(static_cast<unsigned char>(*fcr.ptr)));
}

// extract the string
if(++fcr.ptr < end)
f.s = std::string(fcr.ptr, end - 1);
else
is.setstate(std::ios::failbit);
}
return is;
}

std::ostream& operator<<(std::ostream& os, const foo& f) {
for(int i = 0; i < 3; ++i) {
os << f.a[i] << ',';
}
return os << '\'' << f.s << "'\n";
}

int main(int argc, char* argv[]) {
std::ifstream ifs;
if(argc >= 2) {
ifs.open(argv[1]); // if a filename is given as argument
if(!ifs) {
std::perror(argv[1]);
return 1;
}
} else {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
}

std::istream& is = argc >= 2 ? ifs : std::cin;

// ignore the first line - it's of no use in this demo
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

// read all `foo`s from the stream
std::uintmax_t co = 0;
std::for_each(std::istream_iterator<foo>(is), std::istream_iterator<foo>(),
[&co](const foo& f) {
// Process each foo here
// Just counting them for demo purposes:
++co;
});
std::cout << co << '\n';
}

My test runs on a file with 1'000'000'000 lines with content looking like below:

2,2,2,'abcd'
2, 2,2,'abcd'
2, 2, 2,'abcd'
2, 2, 2, 'abcd'

Unix time wc datafile

1000000000  2500000000 14500000000 datafile

real 1m53.440s
user 1m48.001s
sys 0m3.215s

time ./my_from_chars_prog datafile

1000000000

real 1m43.471s
user 1m28.247s
sys 0m5.622s

From this comparison I think one can see that my_from_chars_prog is able to successfully parse all entries pretty fast. It was consistently faster at doing so than wc - a standard unix tool whos only purpose is to count lines, words and characters.

How to read a line from the console in C?

You need dynamic memory management, and use the fgets function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:

char * getline(void) {
char * line = malloc(100), * linep = line;
size_t lenmax = 100, len = lenmax;
int c;

if(line == NULL)
return NULL;

for(;;) {
c = fgetc(stdin);
if(c == EOF)
break;

if(--len == 0) {
len = lenmax;
char * linen = realloc(linep, lenmax *= 2);

if(linen == NULL) {
free(linep);
return NULL;
}
line = linen + (line - linep);
linep = linen;
}

if((*line++ = c) == '\n')
break;
}
*line = '\0';
return linep;
}

Note: Never use gets ! It does not do bounds checking and can overflow your buffer

Reading whole input instead of single line

fgets() will stop once it encounters a newline. So, you can't workaround it to read multiple lines. So, you'll have to look at alternatives.

One way is is use getchar() is a loop and read as long as there's a room in the buffer or EOF is received.:

int main(void) {

char string[1000];
size_t i = 0;

do {
int ch = getchar();
if (ch == EOF) break;
string[i] = ch;
i++;
} while (i < sizeof string - 1);
string[i] = 0;

makeUpper(string);
return 0;
}

Remember, ctrl+Z works on Windows (to send EOF). On *nix-like systems, you'll have to use Ctrl+D to send EOF.



Related Topics



Leave a reply



Submit