简体   繁体   English

创建字符串向量:C ++

[英]Creating a vector of strings : C++

I am trying to create a vector which should input strings (white space included) until user enters '!' 我正在尝试创建一个矢量,该矢量应该输入strings (white space included)直到用户输入'!'为止'!' .

Below is my code : 下面是我的代码:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using namespace std;


int main()
{

   char buffer[100];
   string temp;
   vector <string> vec;


    while(1)//Shows Segmentation fault error while running,
    //compiles succesfully
    {
    cout << "Enter String : ";
    cin.get(buffer,100,'\n');//To ensure that whitespaces are also input
    cout << "@@@@ " << buffer << endl ;//Shows correct input

    cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    //Clearing cin stream for any residual characters
    temp.assign(buffer);//Assigning string the input "phrase"
    cout << "###" << temp << endl;//Shows correct output

    if (temp == "!") //if input is '!' character do not push on the vector a
    //come out of the loop
    break;

    vec.push_back(temp);//push on the vector
    temp.assign(NULL); //flush temp string

    }


  vector <string>::iterator p = vec.begin();
  //display thre vector
  while( p != vec.end())
   {
       cout << *p << endl;
       p++;
       }

    return 0;
    }

It compiles successfully but at run-time throws Segmentation fault error. 它可以成功编译,但在运行时会引发Segmentation fault错误。

Not able to figure out why ? 不知道为什么? Can any one point out? 有人可以指出吗?

Also smarter solution for this, is appreciated along side pointing out what is wrong with my code. 同时指出这一点更聪明的解决方案,是指出我的代码有什么问题。

Thanks 谢谢

This will be the cause: 这将是原因:

temp.assign(NULL);

as std::string::assign() will attempt to read until a null terminator is found and dereferencing a NULL pointer is undefined behaviour: in this case a segmentation fault. as std::string::assign()将尝试读取,直到找到空终止符并且取消引用NULL指针的行为尚未定义:在这种情况下为分段错误。 Use temp.clear() or just create a new object on each iteration. 使用temp.clear()或在每次迭代中创建一个新对象。

Use std::getline() which reads lines including whitespace and avoids having to hardcode a fixed size array (ie buffer[100] ): 使用std::getline()读取包括空格的行,并避免对固定大小的数组(即buffer[100] )进行硬编码:

std::string line;
while (std::getline(std::cin, line) && line != "!")
{
    vec.push_back(line);
}

Other problems notwithstanding, running your program in gdb (or probably any other debugger) reveals the reason: 尽管存在其他问题,但在gdb (或可能是其他任何调试器)中运行程序gdb以下原因:

tikal@seven ~$ g++ -o temp temp.cpp
tikal@seven ~$ gdb temp
GNU gdb 6.3.50-20050815 (Apple version gdb-1822) (Sun Aug  5 03:00:42 UTC 2012)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries ... done

(gdb) run
Starting program: /Users/tikal/temp 
Reading symbols for shared libraries ++............................. done
Enter String : asd
@@@@ asd
###asd

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00007fff9081e6b0 in strlen ()
(gdb) backtrace
#0  0x00007fff9081e6b0 in strlen ()
#1  0x00007fff9857ab95 in std::string::assign ()
#2  0x0000000100001642 in main ()
(gdb) 

Essentially, temp.assign( NULL ) is a bad idea. 本质上, temp.assign( NULL )是个坏主意。 You could use temp.clear() instead, or don't bother clearing it (you'll just reassign it later). 您可以改用temp.clear() ,也可以不用清除它(以后再重新分配)。

while (getline(cin, temp) && temp != "!")
{
    vec.push_back(temp);
}

Using buffers like that is more a C thing to do than C++. 与C ++相比,使用此类缓冲区更是C的工作。 In C++ there's usually a way to avoid such explicit memory management using classes -- this is a good example. 在C ++中,通常有一种避免使用类进行显式内存管理的方法-这是一个很好的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM