如何在C++中读取一串字符串

How to read in a bunch of strings in C++?

本文关键字:一串 字符串 读取 C++      更新时间:2023-10-16

我需要在不事先知道有多少字符串的情况下读取一堆字符串,并在读取时打印它们。所以我决定使用while(!feof(stdin))作为EOF指标。这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{ 
    char* str; 
    std::cout<<"nEnter strings:";
    while(!feof(stdin))
    {  
        std::cin>>str;
        std::cout<<"nThe string you entered is"<<str;
    }
    return 0;
}

由于某种原因,上面的代码在我输入第一个字符串后说segmentation fault。有人能建议解决这个问题吗。

您需要为要读取的字符串分配一些内存。

你目前所拥有的只是堆栈上指向某个随机内存区域的指针,这意味着当你读取字符时,它们会践踏其他数据,甚至是不允许写入的内存,这会导致segfault。

试图分配一些内存的问题是,在字符串被读入之前,你不知道要分配多少…(你可以说"300个字符",看看它是否足够。但如果不足够,你也会遇到同样的数据损坏问题(

最好使用C++std::string类型。

str是指向char的指针。当你试图在那里写作时,它没有指向任何有效的地方。

在C++中尝试某种形式的new,或者,更好的是,由于您正在编写C++,请使用std::string

str被声明为char* str,这意味着它实际上不是一个字符串(只是一个指向它的指针,未初始化的BTW(,并且没有为它分配任何空间。这就是它分段失败的原因。由于你用c++编程,你可以使用

std::string str;

它会起作用的。别忘了#include <string>

当应用程序试图访问不允许访问的内存位置时,会发生分段错误。在您的情况下,问题是您正在取消引用一个未初始化的指针:char* str;

一个可能的解决方案是将指针更改为具有适当大小的数组

这样的东西可能就足够了:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{ 
    char str[20]; 
    cout<<"nEnter strings:";
    while(!feof(stdin))
    { 
       cin.width(20); //set a limit
       cin>>str;
       cout<<"nThe string you entered is"<<str;
    }
    return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main(void)
{ 
    std::string str[300]; 
    std::cout<<"nEnter strings:";
    while(!std::cin.eof())
    {  
        std::cin>>str;
        std::cout<<"nThe string you entered is"<<str;
    }
    return 0;
}

应该做的技巧