英文:
how to print sentences with spaces from a txt?
问题
我试图从 input.txt 文件复制文本,但程序将空格视为换行符。我应该如何处理这个问题?
我的 input.txt (试验)
- hero
- angelic
- hello world
- demons
我的 source.c
int main(void) {
FILE* fread = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
if (fread == NULL) {
printf("一个文件无法打开!\n");
return -1;
}
// 这将从 input.txt 中粘贴文本到命令行
char line[1000] = "";
while (fscanf(fread, "%s", line) == 1) {
printf("%s\n", line);
}
fclose(fread);
fclose(fwrite);
}
输出
hero
2.
angelic
3.
hello
world
4.
demons
英文:
I'm trying to copy text from a input.txt but programs thinks spaces are new lines. How should I go about this?
my input.txt (trial)
1. hero
2. angelic
3. hello world
4. demons
my source.c
int main(void) {
FILE* fread = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
if (fread == NULL) {
printf("One file wouldn't open!\n");
return -1;
}
//this pastes the text from input.txt into the command-line
char line[1000] = "";
while (fscanf(fread, "%s", line) == 1) {
printf("%s\n", line);
}
fclose(fread);
fclose(fwrite);
output
1.
hero
2.
angelic
3.
hello
world
4.
demons
答案1
得分: 1
这是您要做的事情。已经有一个实现这个功能的函数可以帮助您完成这个任务。
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
if (fp == NULL){
printf("无法打开文件!\n");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
printf("读取到长度为 %zu 的行:\n", read);
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
英文:
Here is what you do. There is already function implemented to help you in doing this.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
if (fp == NULL){
printf("One file wouldn't open!\n");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论