如何在C++中读取一串字符串
How to read in a bunch of strings in C++?
我需要在不事先知道有多少字符串的情况下读取一堆字符串,并在读取时打印它们。所以我决定使用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;
}
应该做的技巧
相关文章:
- C++为一串单词添加空格
- 如何使用regex_replace将子字符串替换为字符串中的另一个子字符串,同时保持整个文本完整?
- 如果我有很多具有相似前缀的字符串,是否有理由从该前缀创建一个子字符串?
- 为什么Visual Studio正在清除我的一串反斜杠
- 用C++替换std::字符串中的一个子字符串,但不能全部替换
- 如何将内存中的位转换为一串和零?
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- UnicodeString 将一个子字符串替换为另一个子字符串
- 编码大于原始文本:如何获取零和一的字符串并将它们作为实际字节写入文件
- 创建一个程序,该程序将一串数字作为输入,并输出偶数和奇数的总和
- C++ 如何对一串数字求平均值
- C 一组字符串的所有布置
- 在 c++ 中,在 for 循环中,你如何打印出一次字符串
- 从网络数据包复制一串 wchar 时访问冲突
- 从向量<T>创建一组字符串
- C - 将文本文件读为一串单词,然后将字符串分为向量
- 我如何在一串随机生成的字母I C 中查找一个单词
- 从一串数字C++创建一个数字序列
- 在另一个字符串中查找一串数字
- 如何在C++中读取一串字符串