【问题标题】:why my cpp code can't run?(about char*[])为什么我的 cpp 代码无法运行?(关于 char*[])
【发布时间】:2021-06-22 10:57:57
【问题描述】:

这是我的代码

错误是分段错误,我不明白为什么

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring> 

using namespace std;

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

    int i = 0;

    do
    {
        cin >> szword[i];
        cout << szword[i];
        i++;
    }while(strcmp(szword[i - 1], "done"));

    cout << i + 1;

    return 0;
}

【问题讨论】:

标签: c++ loops input do-while c-strings


【解决方案1】:

首先,您的程序中没有使用来自标头 &lt;cstdio&gt;&lt;string&gt; 的声明。所以你应该删除这些指令

#include <cstdio>
#include <string>

您声明了一个元素类型为char * 的初始化数组。因此这种说法

cin >> szword[i];

调用未定义的行为,因为指针 szword[i] 具有不确定的值。

而且这个调用即使操作符的参数是正确的

cin >> szword[i];

可能会失败。您应该检查它是否成功。而且我认为输出字符串"done"没有太大意义。

也在此声明中

cout << i + 1;

您输出的值大于输入的字符串数。

如果使用字符数组,那么您的程序可能如下所示

#include <iostream>
#include <cstring>

int main() 
{
    const size_t N = 100;
    char szword[N][N];
    
    size_t i = 0;
    while ( std::cin.getline( szword[i], sizeof( szword[i] ) ) && 
            std::strcmp( szword[i], "done" ) != 0 )
    {
        std::cout << szword[i++] << '\n';
    }
    
    std::cout << i << '\n';
    
    return 0;
} 

程序输出可能看起来像

Hello
World
2

【讨论】:

    【解决方案2】:

    下面的代码可以正常工作,如果你想使用 char *,对于 C++ 字符串你可以使用 C++ 版本

    C版:

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring> 
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
      char *tmp;
      int i = 0;
    
    do
    {
        cin >> tmp;
        cout << tmp;
        i++;
    }while(strcmp(tmp, "done"));
    
    cout << i + 1;
    
    return 0;
    }
    

    C++ 版本:

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring> 
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
      string tmp;
      int i = 0;
    
    do
    {
        cin >> tmp;
        cout << tmp;
        i++;
    }while(tmp != "done"));
    
    cout << i + 1;
    
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多