我想在C中创建一个程序,该程序将任意数量的任意长度的行作为输入,然后打印以控制台输入的最后一行。例如:
输入:
hi
my name is
david
Run Code Online (Sandbox Code Playgroud)
输出: david
我认为最好的方法是有一个循环,将每一行作为输入并将其存储在char数组中,因此在循环结束时,最后一行最终是存储在char数组中的内容,可以打印出来。
到目前为止,我只用C进行过一次讲座,所以我认为我一直在用Java / C ++思维方式设置错误,因为我对这些语言有更多的经验。
这是我到目前为止的内容,但我知道这还远没有正确:
#include <stdio.h>
int main()
{
printf("Enter some lines of strings: \n");
char line[50];
for(int i = 0; i < 10; i++){
line = getline(); //I know this is inproper syntax but I want to do something like this
}
printf("%s",line);
}
Run Code Online (Sandbox Code Playgroud)
我也i < 10处于循环中,因为我不知道如何查找输入中的总行数,这将是循环执行此操作的适当时间。同样,输入是从
./program < test.txt
Run Code Online (Sandbox Code Playgroud)
Unix shell中的命令,其中test.txt有输入。
用途fgets():
while (fgets(line, sizeof line, stdin)) {
// don't need to do anything here
}
printf("%s", line);
Run Code Online (Sandbox Code Playgroud)
您不需要限制迭代次数。在文件末尾,fgets()返回NULL并且不修改缓冲区,因此line仍将保留已读取的最后一行。