【问题标题】:Printing a substring from an argument in C [duplicate]从C中的参数打印子字符串[重复]
【发布时间】:2019-09-17 20:03:54
【问题描述】:

我需要编写一个程序,在第一行打印第一个字符,然后在下一行打印后两个字符。即Hello

H

他

帮助

地狱

你好

这是我迄今为止尝试过的,但我每行只收到一个字母。

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

int main(int argc, char *argv[])
{
    for(int i = 1; i < argc; i++)
    {
      int wordLength = strlen(argv[i]);
      for(int j = 0; j < wordLength; j++)
      {
        printf("%c\n", *argv + i);
      }
    }
    return 0;
}

【问题讨论】:

  • 在这里你明确地说只打印一个字符:printf("%c\n"...
  • 试试printf("%.*s\n", j+1, argv[i])。

标签: c printf


【解决方案1】:

通过对您的代码进行微小的更改,这是正确的版本。

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

int main(int argc, char *argv[])
{

    for(int i = 1; i < argc; i++)
        {
        int wordLength = strlen(argv[i]);

        for(int j = 0; j < wordLength; j++)
        {
            for (int k=0;k<=j;k++){
                printf("%c", argv[i][k]);
            }
                printf("\n");
        }
        }
    return 0;
}

编译运行

gcc -Wall file.c -o file

./file salam hello

输出

s
sa
sal
sala
salam
h
he
hel
hell
hello

【讨论】:

    猜你喜欢
    • 2010-12-23
    • 1970-01-01
    • 2021-04-19
    • 2017-02-02
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多