gpt4 book ai didi

C++ 字符串、标点符号、数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:52:47 29 4
gpt4 key购买 nike

我需要能够仅使用 C++ 字符串才能更改下面的输入段落。我遇到的问题是,当我在末尾拉出带有标点符号的东西时,例如“programs-”,它会将它作为“programs-”拉入我的数组,而不是分别将“programs”和“-”拉入我的数组。我需要知道如何执行此操作,以便我可以将所有“-”替换为“.”。

如何将两者分开并将它们分别放在数组中它自己的 block 中?

#include <iostream>
#include <fstream>

using namespace std;


void read(string line[], string para[], int &d)
{
string temp;
int i = 0;

ifstream myfile ("paragraphwordsub.txt");
if (myfile.is_open())
{
while ( temp != "$" )
{
myfile >> temp;
line [i] = temp;
cout << line[i] << " ";
i++;
}
cout << endl;
i=0;
while (!myfile.eof())
{
myfile >> temp;
para[i] = temp;
cout << para[i] << " ";
d++;
i++;
}

myfile.close();
}

else cout << "Unable to open file";

cout << endl << endl << i << endl << para[73] << endl;

return;

}

int main()
{
int const SIZE = 100;
string a [SIZE];
string b [SIZE];
int counter = 0;

read(a, b, counter);

cout << endl << endl << counter << endl;


return 0;

}

输入:

Whose programs is such? There were important programs to be done and Tommy were asked to do such- Tommy were sure Sam would do such- Samson could have done such, but Nicholsonnders did such- Sam got angry about that, because such were Tommy's programs- Tommy thought Samson could do such but Nicholsonnders realized that Tommy wouldn't do such- It ended up that Tommy blamed Sam when Nicholsonnders did what Samson could have done-

最佳答案

如果我对问题的理解正确,你想在你的输入中找到子字符串“-”的每一次出现并将其替换为子字符串“.”。

您可能一直希望因为 operator>> 从输入中一次读取一个“单词”,所以它会在“programs”的最后一个字母之后停止;但实际上它仅在涉及到空白或输入结束时才停止。似乎希望有一个流操纵器,您可以使用它来告诉它在标点符号处停止,但我不知道有任何这样的操纵器。

你可以尝试这样的事情:

myfile >> temp;
size_t position = temp.find("-");
while (found!=std::string::npos) {
temp.replace(position, 1, ".");
}

如果你使用字符串变量而不是文字“-”和“.”,你可以概括它来进行任何你想要的替换(但是代替常量 1 在 replace() 的参数中,你必须使用要替换的子串的长度)。

关于C++ 字符串、标点符号、数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22799454/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com