【问题标题】:Find Nth Word given a file of Strings and ints C给定一个字符串和整数文件,查找第 N 个单词 C
【发布时间】:2017-02-16 01:52:16
【问题描述】:

我需要在 Unix 中通过重定向运算符通过标准输入给出的字符串中找到第 N 个单词。 输入是这样的:

但我必须向你解释所有这些谴责快乐和赞美痛苦的错误观念是如何产生的
5
欧洲语言是同一个家族的成员。
3

谁能告诉我如何将字符串读入 char 数组,然后获取 int 并使用它来查找给定的单词?我已经使用了一段时间,但无法使其正常工作。

#define INPUT_LENGTH 400
int main(void)
{

char input[INPUT_LENGTH];
char integer[INPUT_LENGTH];
int spaces = 0;
int value;
char n;

while(fgets(input, INPUT_LENGTH, stdin)) //read in string line
  {
    while(fgets(integer, INPUT_LENGTH,stdin)) //read in int
      {
        int num = sscanf(integer, "%d", &value); //assign int val to num
           while(1 == sscanf(input, "%c", &n)) //go through string one char at a time
              if(spaces == num && !isspace(n))
                printf("%c", n); //print chars if we've reached the word
              else if(isspace(n))
                spaces++;
      }      
   }
}

我已经考虑到 cmets 重做了大部分工作,但不幸的是,它似乎仍然无法通过操作员实际读取输入。 我不确定,但我认为我的 fget 不正确。我对 C 比较陌生,即使经过研究也不完全确定他们如何处理数据

【问题讨论】:

  • 您的问题不在 SO 范围内,因为您需要证明已为找到解决方案做出了一些初步努力。您应该阅读一些关于 c 中 io 和字符串处理的教程,尝试一下,然后返回您遇到的一些特定问题。如果你有一些你写过的代码,你应该把它贴出来。
  • 你试过什么?为了避免可能的反对票并获得一个好的答案,您可能需要修改您的问题以更具体地说明您遇到的问题。你可能想仔细阅读……How do I ask a good question?……和How to create a Minimal, Complete, and Verifiable example
  • while 循环的空循环体是错误的——删除那个分号。您需要读取包含字符串的一行,然后读取包含数字的第二行。您需要两个数组来保存线条。然后你需要use sscanf() in a loop来解析单词。

标签: c string char stdin


【解决方案1】:

像这样使用strtok

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

#define INPUT_LENGTH 400

int main(void){
    char input[INPUT_LENGTH];
    char integer[INPUT_LENGTH];
    int value;

    while(fgets(input, sizeof input, stdin)) //read in string line
    {
        if(fgets(integer, sizeof integer, stdin)) //read in int
        {
            if(1==sscanf(integer, "%d", &value)) //assign int value to value
            {
                char *word = strtok(input, " \t\n");
                int n;
                for(n = 1; word != NULL && n < value; ++n){// 1 origin
                    word = strtok(NULL, " \t\n");
                }
                if(word != NULL && n == value)
                    puts(word);//Nth word
                else
                    puts("No word");
            }
            else {
                printf("Numerical value is not specified.\n");
            }
        }
        else {
            printf("There is no numeric specification line.\n");
        }
    }
}

【讨论】:

  • 对不起!我应该提到的部分任务是在不标记字符串的情况下完成它,当我尝试使用 ./NthWord
  • @NicholasNickNic nthword.txt 的内容是什么?它似乎工作。 DEMO
猜你喜欢
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多