C语言处理多行字符串输入遇问题:代码无输出请求排查
Let's break down the problem with your code first, then walk through solutions to get it working as expected.
The Root Cause
When you use scanf("%d", &t) to read the integer 3, it leaves the newline character (\n) you pressed after entering the number in the input buffer.
Your next line uses scanf("%[^\n]%*c", a) to read a line of text. Unlike other format specifiers like %s, the %[^\n] pattern does not skip leading whitespace. So it immediately hits the leftover newline character, fails to match any text, and returns 0 instead of 1. This means your loop never runs—hence, no output.
Fixes to Try
Fix 1: Consume the Leftover Newline
Add a getchar() right after reading the integer to eat the newline left in the buffer:
#include <stdio.h> int main(){ int t; scanf("%d",&t); getchar(); // Reads the newline after the integer char a[100]; while(scanf("%[^\n]%*c",a) == 1){ printf("%s\n",a); --t; if(t == 0) break; } return 0; }
Fix 2: Skip Whitespace in the String Scan
Modify the format string to include a leading space—this tells scanf to skip any leading whitespace (including newlines and spaces) before reading the string:
#include <stdio.h> int main(){ int t; scanf("%d",&t); char a[100]; // Leading space skips whitespace before reading the line while(scanf(" %[^\n]%*c",a) == 1){ printf("%s\n",a); --t; if(t == 0) break; } return 0; }
Fix 3: Use fgets for Safer Line Reading
scanf("%[^\n]") can cause buffer overflow if the line is longer than your array size. fgets is safer because it enforces a character limit. Here's how to use it:
#include <stdio.h> #include <string.h> // For strcspn int main(){ int t; scanf("%d",&t); getchar(); // Consume the newline after the integer char a[100]; while(fgets(a, sizeof(a), stdin) != NULL && t > 0){ // Remove the trailing newline that fgets includes a[strcspn(a, "\n")] = '\0'; printf("%s\n",a); --t; } return 0; }
For Your Specific Example Input
If you only want to print the single line after the integer (ignoring the loop for t), simplify the code like this:
#include <stdio.h> int main(){ int t; scanf("%d", &t); char a[100]; scanf(" %[^\n]", a); // Skips space after 3, reads rest of the line printf("%s\n", a); return 0; }
This will output exactly the string you expect from your example input.
内容的提问来源于stack exchange,提问作者chelsea

