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

时间:2019-03-29 21:56:40

标签: 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]

1 个答案:

答案 0 :(得分:1)

您想要的:

#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]