我有一个应该接受像
这样的段落的程序Testing#the hash#tag
#program!#when #beginning? a line
or #also a #comma,
并输出类似
的内容#the
#tag
#program
#when
#beginning
#also
#comma,
我觉得逻辑是有道理的,但显然不是因为程序似乎永远不会进入输入线。问题几乎肯定在下面的最后一个源文件中。
这是主要的源程序
#include "HashTagger.h"
#include <string>
#include <iostream>
using namespace hw02;
using namespace std;
int main() {
// Construct an object for extracting the
// hashtags.
HashTagger hashTagger;
// Read the standard input and extract the
// hashtags.
while (true) {
// Read one line from the standard input.
string line;
getline(cin, line);
if (!cin) {
break;
}
// Get all of the hashtags on the line.
hashTagger.getTags(line);
}
// Print the hashtags.
hashTagger.printTags();
// Return the status.
return 0;
}
我的头文件
#ifndef HASHTAGGER_H
#define HASHTAGGER_H
#include <string>
namespace hw02 {
class HashTagger {
public:
void getTags(std::string line);
void printTags();
private:
std::string hashtags_;
};
}
#endif
和源文件 源文件中的测试似乎表明程序只到达第二行然后在抓取最后2个主题标签之前停止
#include "HashTagger.h"
#include <iostream>
using namespace std;
using namespace hw02;
void HashTagger::getTags(string line) {
// Loop over all characters in a line that can begin a hashtag
int b = 0;
string hashtags_ = "";
for (unsigned int j = 0; j < line.length(); ++j) {
char c = line.at(j);
// if "#" is found assign beginning of capture to b
if (c == '#') {
b = j;
// if the beginning is less than the end space, newline, ".", "?", or "!" found, add substring of the hashtag to hashtags_
}
if (b < j && (c == ' ' || c == '\n' || c == '.' || c == '?' || c == '!' )) {
hashtags_ = hashtags_ + "\n" + line.substr(b, j - b + 1);
b = 0;
//Test// cout << b << "/" << j << "/" << c << "/" << hashtags_ << "/" << endl;
}
}
}
void HashTagger::printTags() {
// print out hashtags_ to the console
cout << hashtags_ << endl;
}
答案 0 :(得分:0)
您正在hashtags_
功能中重新声明getTags
。因此,所有字符串修改都对局部变量而不是类成员变量进行操作。
更改行
string hashtags_ = "";
到
hashtags_ = "";
为了避免重新声明并对稍后用于输出的类成员变量进行操作。
此外,请确保您的输入以两个换行符(\n\n
)终止,以避免break
过早退出主循环,或移动您的支票和break
getTags
电话后的声明:
while (true) {
// Read one line from the standard input.
string line;
getline(cin, line);
// Get all of the hashtags on the line.
hashTagger.getTags(line);
if (!cin) {
break;
}
}