Reputation: 29
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character.
int numArrayCount = 0;
int num, count = 0;
int binaryArray[CAPACITY];
int numArray[CAPACITY];
//takes in positive numbers higher than zero and less than 64.
//End output with Ctrl+Z
while (scanf_s( "%d", &num ) == 1) {
if (num < 64 && num > 0) {
binaryArray[ count++ ] = base10ToBinary(num);
numArray[ numArrayCount++ ] = num;
}
}
Upvotes: 0
Views: 2170
Reputation: 153447
How can I stop input with newline character (?)
Look for the '\n'
with getchar()
before scanf( "%d", &num )
as "%d"
quietly consumes leading white-space including '\n'
.
// concept code
int ch;
while (isspace(c = getchar())) {
if (c == '\n') return "We are done, \\n"
}
if (c == EOF) return "We are done, EOF"
// put back
ungetc(c, stdin);
if (scanf( "%d", &num ) != 1) return "Non-numeric input";
return "Success";
Full solution here for float
.
An alternative approach uses fgets()
and then pares the string. This good approach does has trouble with long line management and fails should the line of input include an uncommon null character.
Upvotes: 1
Reputation: 1
while (scanf_s(" %d", &num) == 1) {
Insert a space before the %d
as it will make the scanf function disregard the input that was leftover from whatever was left in stdin and you won't need that getchar() anymore.
Upvotes: 0
Reputation: 148890
There is no direct way, because scanf
and friends are only a poor man's parser. As long as you have values separated with an arbitrary number of space characters (space, tab, return, linefeed and vtab) and it does not matter what those separators are, scanf
is fine.
If you want to process lines, and then can parse the content of a line, fgets
is the way to go. Unfortunately, you cannot repeatedly scan from a string, but you can build nice string parsers with strtok
or better strcspn
Other languages (C++, Java, etc.) or maybe other libraries may have smarter tools. But C was initially build as a low level language...
Upvotes: 1