在 C 中读取带有整数和字符串的外部文件

发布于 2024-11-07 20:27:53 字数 366 浏览 0 评论 0原文

我正在尝试读取外部文本文件。该文件包含以下形式的数字和单词:(

hello 1239 4943 melissa

每个元素独占一行)实际文本文件有超过 1200 个单词。我想读取每一行并将它们存储为字符串,但 fscanf 会跳过数字。如何将数字读入程序并将它们存储为字符串?

    char word[1263][13];
    FILE * fh;

    fh=fopen("wordlist.txt","r");
    for (a=0;a<1263;a++)
    {
      fscanf(fh,"%s",word[a]);
    }
    fclose(fh);

I am trying to read an external text file. The file contains both numbers and words in the form:

hello 1239 4943 melissa

(with each element on its own line) The actual text file has over 1200 words. I want to read each line and store them as strings, but fscanf skips over the numbers. How can I read the numbers into my program and store them as strings?

    char word[1263][13];
    FILE * fh;

    fh=fopen("wordlist.txt","r");
    for (a=0;a<1263;a++)
    {
      fscanf(fh,"%s",word[a]);
    }
    fclose(fh);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

命比纸薄 2024-11-14 20:27:53

您应该能够通过 fscanf 实现这一点

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( int argc, char ** argv ) {
   FILE * source_file;

   char * buffer = malloc( 100 * sizeof(char));     
   char ret = '\0';

   source_file = fopen("TENLINES.TXT","r+");
   do {
      ret = fscanf(source_file, "%s", buffer);
      printf("%s\n", buffer);

   } while (ret != EOF);

   return 0;
}

You should be able to achieve this via fscanf

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( int argc, char ** argv ) {
   FILE * source_file;

   char * buffer = malloc( 100 * sizeof(char));     
   char ret = '\0';

   source_file = fopen("TENLINES.TXT","r+");
   do {
      ret = fscanf(source_file, "%s", buffer);
      printf("%s\n", buffer);

   } while (ret != EOF);

   return 0;
}
乱了心跳 2024-11-14 20:27:53

您如何使用fscanf?以下代码将起作用:

char s1[100];
int i1;
int i2;
char s2[100];

while (!feof (file))
  {
    // Should check return value.
    fscanf (file, "%s %d %d %s", s1, &i1, &i2, s2);
    printf ("%s %d %d %s\n", s1, i1, i2, s2);
  }

How are you using fscanf? The following code will work:

char s1[100];
int i1;
int i2;
char s2[100];

while (!feof (file))
  {
    // Should check return value.
    fscanf (file, "%s %d %d %s", s1, &i1, &i2, s2);
    printf ("%s %d %d %s\n", s1, i1, i2, s2);
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文