在C语言中,消除行末空格可以通过以下几种方法实现:
使用`getline`函数读取整行并去除末尾空格
```c
include include int main() { char line; while (getline(&line, sizeof(line)) > 0) { // 去除末尾空格 for (int i = strlen(line) - 1; i >= 0; i--) { if (line[i] != '\n' && line[i] != ' ') { line[i] = '\0'; break; } } printf("%s", line); } return 0; } ``` ```c include include char *rtrim(char *str) { if (str == NULL || *str == '\0') { return str; } int len = strlen(str); char *p = str + len - 1; while (p >= str && isspace(*p)) { *p = '\0'; p--; } return str; } int main() { char line; while (fgets(line, sizeof(line), stdin)) { printf("%s", rtrim(line)); } return 0; } ``` ```c include include void removeSpaces(char *str) { int i = 0, j = 0; int length = strlen(str); for (i = 0; i < length; i++) { if (str[i] != ' ') { str[j++] = str[i]; } } str[j] = '\0'; } int main() { char line; while (fgets(line, sizeof(line), stdin)) { removeSpaces(line); printf("%s", line); } return 0; } ``` ```c include int main() { int n, i, j, k; scanf("%d", &n); for (k = 1; k <= n; k++) { for (i = 0; i < n; i++) { if (i != n - 1) { printf("%d ", k); } else { printf("%d", k); } } printf("\n"); } return 0; } ``` 这些方法可以根据具体需求选择使用,以达到消除行末空格的目的。使用`rtrim`函数去除字符串末尾的空格
使用双指针遍历字符串并去除空格
在输出时去除末尾空格