从scanf读取换行符
read newline from scanf
我试图从stdin输入,使用scanf逐行,但我需要执行一个特定的函数时,只有一个换行符被输入。Scanf似乎不能正确地做这件事,我不能使用fgets,因为程序的其余部分似乎停止工作。帮助吗?
char input[1000];
scanf("%s", input);
if((strcmp(input, "n") == 0) {
// some code
}
似乎不起作用。我只需要在只有换行符和其他任何东西时实现这一点。由于
可以逐行读取scanf
。如果只输入一个新的行字符(例如:当用户按下回车键时,将出现您可以处理的空行。试试这个:
char input[1024];
while (scanf("%1023[^n]n", input) == 1) {
if (input[0] == ' ') {
// handle empty line
continue;
}
// handle non-empty line
}
在这种情况下,输入将始终以空结束,并且不包含'n'
。请注意,scanf
只允许读取尽可能多的字符作为缓冲区的大小减去空字符在结束。此外,scanf
在成功时返回它成功扫描的变量的数量。
使用std::string
, std::getline
和std::basic_string::empty
,我们可以在循环中运行输入,如果用户只是按enter键而不输入任何文本,我们可以检测到并调用函数。在本例中,如果没有输入任何内容,则结束循环。
void no_input()
{
std::cout << "You did not enter anything";
}
int main() {
bool keep_going = true;
while (keep_going)
{
std::string foo;
std::cout << "Enter command: ";
std::getline(std::cin, foo);
if (foo.empty())
{
no_input();
keep_going = false;
}
}
}
<<p> 生活例子/kbd> 相关文章:
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 为什么 ifstream 文件中的换行符 - 当被此代码读取时 - 占用 2 个字节
- 使用 getline 读取字符串,但每行中都有换行符
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- 如何使用ifstream c ++从带有换行符的文件读取字符串
- 您如何做到这一点,以便在C++中读取文件时在文件末尾有换行符
- 使用 c++ 读取文件时省略换行符
- 读取文件内容时未定义的字符,文件末尾没有换行符
- 如何仅当字符串流包含任何换行符时才从字符串流中读取行
- 为什么此代码在遇到换行符之前无法正确读取字符串?
- 读取整数对,直到文本输入文件中的换行符
- 正在读取由换行符分隔的文本文件.unix上的C++
- 编写一个C++ pgm 以从文件"input.txt"读取,每当遇到句点时插入换行符并将修改的内容写入"output.txt"
- 如何将换行符按钮更改为空格以完成从输入流的读取
- 使用 getline 仅读取换行符或文本
- 非常简单的C ++:在 fstream 中>>运算符在读取某些内容后是否删除换行符?
- 从文件读取数据时意外标记"换行符"附近出现语法错误
- 读取带引号的 CSV 数据,不带换行符作为结束行
- 从用换行符和逗号分隔的txt文件中读取