
Zitat von
Einstein
Da stellt sich mir die Frage woher weiß das "Programm" jetzt das der Input eine Zahl sein muss ?
Das tut es eben nicht:
Code:
a@DESKTOP-JU125PR:/tmp$ cat einstein.cpp
#include <iostream>
int main() {
int a;
std::cin >> a;
std::cout << a << '\n';
}
a@DESKTOP-JU125PR:/tmp$ g++ -o einstein einstein.cpp
a@DESKTOP-JU125PR:/tmp$ ./einstein
das hier ist gar keine Zahl
0
a@DESKTOP-JU125PR:/tmp$
Ich geb Text ein und das wird "akzeptiert". std::cin will in eine Zahl schreiben -- wenn halt was anderes kommt haste Pech gehabt. Mir fällt gerade kein Weg (mit std::iostream) zu erkennen ob das was eingegeben wurde auch das richtige Format hatte.
Sonst würde ich es halt so machen:
Code:
a@DESKTOP-JU125PR:/tmp$ cat main.cpp
#include <iostream>
#include <cstdio>
#include <errno.h>
int main() {
int a;
while(1) {
int ret = scanf("%d", &a);
// could an int be read?
if (ret == 1) {
break;
}
// is the stream fucked or has it ended?
else if (ferror(stdin) || feof(stdin)) {
return 0;
}
else {
/* remove the unparsed data from stdin, so the next call to scanf
doesn't read the same data again
todo: find out why fflush(stdin) doesn't work */
getchar();
}
}
std::cout << a << '\n';
}
a@DESKTOP-JU125PR:/tmp$ ./einstein
aaaa
abc
123
123
a@DESKTOP-JU125PR:/tmp$
ist aber glaube ich nicht wirklich Anfängerfreundlich