【问题标题】:Need to start string from a specific spot in C++需要从 C++ 中的特定位置开始字符串
【发布时间】:2013-04-07 20:04:55
【问题描述】:

这是我的代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
string word;
cout << "Insert a name to search for: ";
cin >> word;

ifstream file ("Names.txt");

string line; 
getline(file, line, '.'); 

int i;
for (i = 0; i < line.length(); ++i) {
    if ('A' <= line[i] && line[i] <= 'Z') break;
}

string keyword = line.substr(i);

int cnt = count( istream_iterator<string>(file), istream_iterator<string>(), word);
cout << word << " appears " << cnt << " times. It appears most with " << keyword << ".    keyword" << endl;
return 0;
}

此刻:我可以从包含数千个名称(每行一个)的文本文件中搜索某个名称,然后查看该名称出现了多少次。每行还出现一个带有名称的关键字,它以大写字母开头,以句点结尾。

我的问题:我的代码几乎准备好了,但问题是它从文件开头搜索关键字然后打印出来(因为我的代码还没有做任何其他事情)

我的目标:我希望它从找到 SEARCH 词的行中搜索关键词。例如,如果我搜索 Juliet,它出现了一个关键字 Girl,那么我希望它使用该关键字而不是文件中的 FIRST 关键字打印名称。

我的想法:应该有一种方法可以从单词开始搜索,但我不知道如何。 你能帮我做一个额外的循环,以便它从例如单词 Juliet 开始第二个循环。我不知道如何将 cin 转换为字符序列。因为通常在文本文件中搜索字符串时,字符序列位于 ' 符号之间。

'Juliet'

但我需要获取单词字符串并以某种方式对其进行转换

我的问题:如何将输入单词转换为字符序列以获得字符串的起点

【问题讨论】:

  • 您应该插入了一个标题“我的问题”。
  • 完成了,很抱歉出现文字墙
  • 我不明白这个问题。
  • 有一串来自cin的单词。我需要一个算法来搜索那个词并从这一点开始阅读。我可以从特定字符或字符序列开始搜索,但我不知道如何从输入的单词开始搜索。

标签: c++ string character getline


【解决方案1】:

这样的?这不是一个真正的“算法”,它只是一个简单的循环。

string word;
cout << "Insert a name to search for: ";
cin >> word;
ifstream file ("Names.txt");
string a_word;
while (file >> a_word && a_word != word)
{
}
if (file)
{
    // found word now start second search.
}
else
{
    // error, didn't find word
}       

很抱歉,如果这不正确,但我很难理解您遇到的问题。上面的代码很简单,比你自己写的代码还要简单。

【讨论】:

  • 嗯,是的,对不起,在我的代码中,我还包括了计算单词的部分和另一种算法来搜索从大写字母到句点的额外关键字。感谢您的回答,虽然我不熟悉 C++ 中的 a_string,但我会在几秒钟内测试它
  • 哦,抱歉,您刚刚创建了一个名为 a_word 的新字符串 :)
  • 是的,随意更改变量名。
  • @JackLongen 很高兴为您提供帮助。由于此答案对您有帮助,您能否通过单击绿色勾号来接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多