c - 将字符串插入字符串数组 c

标签 c arrays

我需要一些简单的东西,但不知道为什么用c这么难(我的背景是java),需要将字符串输入到c中的字符串数组,这里是我的代码:

    int n;  
printf("Please enter number of words \n");
scanf_s("%d", &n);
char *a=(int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
    printf("Enter word \n");            
    scanf_s("%s", a[i]);// <--line gives error
}

示例:

Please enter number of words
3
Enter word
aaa
Enter word
bbb
Enter word
ccc  

数组看起来像:[aaa][bbb][ccc]

最佳答案

你想要那个:

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

int main()
{
  int n;  

  printf("Please enter number of words \n");
  if (scanf("%d", &n) != 1)
    fprintf(stderr, "invalid number");
  else if (n <= 0)
    fprintf(stderr, "number is not > 0");
  else {
    char ** a = malloc(n * sizeof(char *));
    char word[16];

    for (int i = 0; i < n; i++)
    {
      printf("Enter word (max length 15)\n");            
      if (scanf("%15s", word) != 1) {
        fprintf("EOF");
        return -1;
      }
      a[i] = strdup(word);
    }

    for (int i = 0; i < n; i++)
      printf("[%s]", a[i]);
    putchar('\n');
  }
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall as.c
pi@raspberrypi:/tmp $ ./a.out
Please enter number of words 
3
Enter word (max length 15)
aze
Enter word (max length 15)
qsd
Enter word (max length 15)
wxc
[aze][qsd][wxc]
<小时/>

请注意,在备注中比较了 C 和 Java,Java 是一种对象语言,而不是 C,比较 Java 和 C++:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
  cout << "Please enter number of words" << endl;

  int n;

  if (!(cin >> n))
    cerr << "invalid number" << endl;
  else if (n <= 0)
    cerr << "number is not > 0" << endl;
  else {
    vector<string> a;
    string word;

    for (int i = 0; i < n; i++)
    {
      cout << "Enter word" << endl;

      if (!(cin >> word)) {
        cerr << "EOF" << endl;
        return -1;
      }
      a.push_back(word);
    }

    for (int i = 0; i < n; i++)
      cout << '[' << a[i] << ']';
    cout << endl;
  }
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall as.cc
pi@raspberrypi:/tmp $ ./a.out
Please enter number of words
3
Enter word
aze
Enter word
qsd
Enter word
wxc
[aze][qsd][wxc]

关于c - 将字符串插入字符串数组 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55425943/

相关文章:

php - array_udiff 返回不同的结果

java - 如何从两个数组中获取所有可能的组合?

python - 使用 numpy.save 保存 Numpy 二维数组列表(数组一起呈锯齿状)

c - 非指令是合法的 c 预处理指令吗?

c - C 函数可能的返回类型

c - 在文件 C 中查找字符串的子字符串

c - 用户输入文件

arrays - 将简单代码集成到复杂代码中

c - 用 C 序列化 double 和 float

java - 如何根据Gson中的key直接获取json中的值