【问题标题】:print and count strings from <tab.txt in C从 C 中的 <tab.txt 打印和计算字符串
【发布时间】:2014-11-01 10:35:33
【问题描述】:

有人可以帮我解决这个问题吗?我是 C 编程的初学者,我不知道如何从标准输入的表中打印字符串以及如何计算有多少字符串...

例如 './program select row 3

int i;

char c(stidn);
int i, *p_i;
p_i = &i;

int select() {
while ((c=getchar()) != EOF)
  {
  i++;
  }
}

int row(){
if (i == (argc 4))
printf("%s\n", p_i);
}

然后我会调用 select 然后 row in main()

if ((argc == 4) && (strcmp("select", argv[1]) == 0)){
  if (argc 4 == p_i)
  {
  row;
  }

我知道这是错误的,但我很伤心......我不知道我能做什么:|

【问题讨论】:

  • 提出一些建议,我们会提供帮助。至少试一试,粘贴您的代码和问题,我们会尽力提供帮助。
  • 你有什么尝试吗?向我们展示您的代码!
  • 您的表格格式如何。即每个字符串都换行,每个字符串由 ;,... 分隔。
  • 它的 getchar() 不是 getcahr()。
  • 这是文本编辑器中的经典表格,其中一行是由“空格”分隔的一些单词和数字,下一行由 Enter 创建

标签: c string printing count


【解决方案1】:

首先我们需要得到正确的行。我们将计算在读取输入时检测到的所有换行符。

unsigned int GoToRow(unsigned int row) //First row has index zero
{
    unsigned int nlCount = 0;
    int c = 0;

    while(nlCount < row  && c != EOF)
    {
        c = getchar();

        if(c == '\n')
        {
            nlCount++;
        }
    }
    return nlCount;
 }

接下来我们需要做的是从输入中获取行。

void GetRow(char* pString, int maxchars)
{
    int charCount = 0;

    while((charCount + 1 < maxchars) || pString[charCount - 1] == '\n')
    {
        pString[charCount] = getchar();
        charCount++;
    }
    pString[charCount] = '\0';
}

我们程序的主要功能

int main(int argc, char** argv)
{
    unsigned int rownumber = 3;
    char rowdata[500];

    if(argc == 4 && (strcmp(argv[1], "select") == 0) && (strcmp(argv[2], "row") == 0))
    {
       rownumber = atoi(argv[3]);
    }

    int rowscounted = GoToRow(rownumber);
    GetRow(rowdata, 500);
    rowscounted++;
    rowscounted += GoToRow((unsigned int)-1); //Go to the end of the data
    printf("Number of rows : %d\n Selected row : %s", rowscounted, rowdata);

    return 0;
}

【讨论】:

  • 但是我不需要计算字符串中的单词,但是表中的所有字符串......并且选择行'x'不在主定义中,但是当我运行程序时它是一个参数控制台
  • 应该使用int c = 0;,而不是char Ref
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
相关资源
最近更新 更多