【问题标题】:getline to split string manipulation errorgetline 拆分字符串操作错误
【发布时间】:2013-09-15 01:46:18
【问题描述】:

大家好,我有一个班级作业,我必须拆分一个字符串并对其进行操作。但是,当我尝试拆分字符串并将其分配给数组时,只有第一个元素出现,而其他两个没有。请帮忙。

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string str;
    cout<<"Enter a first name, middle initial, last name: ";
    cin>> str;
    string word;
    string array[3];
    stringstream stream(str);
    int counter = 0;
    while( getline(stream, word, ' ') )
    {
        cout<<word;
       array[counter] = word;

       counter++;
    }
    cout<<"The "<<array[0].length()<<" characters of the first name are: "<<array[0]<<endl;
    cout<<"The "<<array[2].length()<<" characters of the last name are: "<<array[2]<<endl;
    string newstring = array[2]+", "+array[0]+" "+array[1];
    cout<<"In the phone book, the name would be: "<<newstring<<endl;
    cout<<"The length of the name is: "<<newstring.length()<<endl;
    cout<<"The comma is at position: "<<newstring.find(",")<<endl;
    array[0].swap(array[2]);
    cout<<"After the swap, the last name is "<<array[2]<<" and the first name is "<<array[0];

    system("pause");
    return 0;

}

【问题讨论】:

标签: c++ string getline stdstring


【解决方案1】:

您的代码中有一些明显的错误:

  1. 您需要在尝试阅读后始终检查您的输入!您可以使用 while-loop 执行此操作,但您还需要先验证您是否确实成功读取了字符串。
  2. 看来您正在混合 std::stringstd::getline() 的输入运算符正在执行的操作:输入运算符在跳过前导空格后读取第一个单词,而 std::getline() 读取,嗯,一行(无论是行终止符可以指定为第三个参数)。
  3. 在读取固定大小的数组时,您始终需要确保您读取的内容不超过该数组的大小!您可能对黑客通过使用缓冲区溢出来利用软件感到担忧:假设您实际上确实首先阅读了一行,然后将其拆分为您已经创建了其中一个可利用程序的单词!如果您不想在每个单词之前检查数组中是否有足够的空间,您可以使用例如std::vector&lt;std::string&gt;(这样做也有黑客的问题,即它打开程序拒绝服务攻击,但尽管这仍然是一个问题,但问题相对较小)。

您的程序也存在一些小问题:

  1. 如果您只从字符串流中读取,则应使用std::istringstream,因为无需同时设置std::stringstream 的写入部分。
  2. 程序要求输入“名字、中间名和姓氏”。我会阅读该规范以使用,例如“John, F., Kennedy”,但您似乎希望使用“John F. Kennedy”。我希望使用逗号的一个原因是我没有中间名,即我会输入“Dietmar, , Kühl”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    相关资源
    最近更新 更多