c++ - 如何在使用for循环和数组时更改为c代码

标签 c++ c arrays string for-loop

我使用 C++ 创建了以下代码,但无法将其更改为 C。我尝试使用 c 在末尾显示输出列表,但无法获取列表。我需要 C 语言代码来进行以下 C++ 编码。请帮助我。

#include<iostream>
#include<string.h>
using namespace std;

int main(){
    int num;
    int state;
    int a,b,data[num];
    string element[2];

    cout<<"Enter amount data: ";
    cin>>num;
    for(a=0;a<num;a++){
        cout<<"Enter state: ";
        cin>>state;

        if(state==3){
            element[0]="A";
        } else if(state==10){
            element[1]="B";
        }   
    }
    cout<<"Elements are: ";
    for(b=0;b<num;b++){
        cout<<" "<<element[b];
    }
}

我尝试使用数组但无法获得列表输出

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

 int main(){
     int num;
     int state;
     int a,b,data[num];
     char str[];

     printf("Enter amount data: ");
     //cin>>num;
     scanf("%d",num);
     for(a=0;a<num;a++){
         printf("Enter state: ");
         //cin>>state;
         printf("%d",state);

         if(state==3){
             *str[0]="A";
         } else if(state==10){
             *str[1]="B";
         } 
     }
     printf("Elemets are: ");
     for(b=0;b<num;b++){
         puts(*str[b])
     }
}

最佳答案

让我们从 C++ 代码开始,因为它包含一个错误。

    string element[2];            // Array with 2 string

    cout<<"Enter amount data: ";
    cin>>num;                     // Read a number

    ...

    cout<<"Elements are: ";
    for(b=0;b<num;b++){           // Use the number as limit
        cout<<" "<<element[b];    // Print all string from 0 to number-1
    }

因此,如果我给程序输入 42,程序将访问 element[0]element[1]element[2], element[3], ...., element[41] 但数组只有 2 个元素,因此程序正在访问在数组之外,即程序具有未定义的行为。

将格式错误的 C++ 程序转换为 C 似乎毫无意义,但当然 - 它可以转换为同样格式错误的 C 程序。

对于 C 程序:

Rule #1

Set your compiler to highest warning level and fix all warnings

在 C 编程中,从编译器收到的警告通常表明存在错误。因此,您必须认真对待警告并修复它们。如果编译器只生成一个警告,甚至不要运行您的程序。首先确保您有一个干净的编译(即无警告编译)。

现在用“gcc -Wall”编译你的程序给我:

main.cpp: In function 'main':
main.cpp:8:11: error: array size missing in 'str'
    8 |      char str[];
      |           ^~~
main.cpp:12:14: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
   12 |      scanf("%d",num);
      |             ~^  ~~~
      |              |  |
      |              |  int
      |              int *
main.cpp:19:14: error: invalid type argument of unary '*' (have 'int')
   19 |              *str[0]="A";
      |              ^~~~~~~
main.cpp:21:14: error: invalid type argument of unary '*' (have 'int')
   21 |              *str[1]="B";
      |              ^~~~~~~
main.cpp:26:15: error: invalid type argument of unary '*' (have 'int')
   26 |          puts(*str[b])
      |               ^~~~~~~
main.cpp:26:23: error: expected ';' before '}' token
   26 |          puts(*str[b])
      |                       ^
      |                       ;
   27 |      }
      |      ~                 
main.cpp:7:14: warning: unused variable 'data' [-Wunused-variable]
    7 |      int a,b,data[num];
      |              ^~~~

所以你有 2 个警告(其中一个是实际错误),但更糟糕的是,你还有 5 个错误。所有这些都会告诉您要修复什么。

您的主要问题是字符串!您尝试将 C++ 类型 string 转换为 C 类型字符串的方式是错误的。这里是对 C 中字符串的一些解释。

There is no string type in C !

所以

char str[];   // is NOT in any way compatible with C++ string element[2];

(这实际上是C中的一个错误。)

C 字符串是 char 数组的特殊用法。特殊用法是 char 数组中的一个元素必须具有值 '\0'(也称为 NUL)。然后,该元素发出 END-OF-STRING 信号。

所以考虑一下:

char strA[2] = "A"; // strA[0] is 'A' and strA[1] is '\0'

这样你就得到了一个等于“A”的C字符串。注意:字符串长度为1,但数组仍需要两个字符。这是因为 '\0' 需要一个额外的字符来表示 END-OF-STRING。

因此,如果您想要一个包含两个字符串的数组来保存“A”或“B”,您需要这样做:

 char str[2][2];  // instead of just char str[];

此外,您不能使用 = 为 C 中的字符串赋值。您需要 strcpy (“字符串复制”)。喜欢:

strcpy(str[0], "A");  // instead of str[0] = "A"

最后,要打印后面带有换行符的字符串,只需使用:

puts(str[0]);  // or puts(str[1]);

关于c++ - 如何在使用for循环和数组时更改为c代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567819/

相关文章:

c++ - 如何解决 <<ClassName>> 的 "undefined reference to ` vtable 错误?

c++ - 我们有更多的静态变量内存空间吗?

c++ 什么时候包含 cpp 即使我们有 .h 文件

c# - 已启用的组合框控件在 Windows 10 中看起来已禁用?

C 打开和读取目​​录

C# 按多种不同条件对数组进行排序

无法理解什么是 fflush() 函数

c - 在 C 中表示字符的最佳方式是什么?

python - 加入整数列表

python - 尝试对两个数组求和