gpt4 book ai didi

c++ - 判断一个单词后面是否跟有空格或换行符

转载 作者:行者123 更新时间:2023-11-28 00:40:55 30 4
gpt4 key购买 nike

当前代码:

void LinkedList::readFunct( string file ) {
string word;
string trailing_char;
stringstream ss;

ifstream infile ( file.c_str() );
while ( getline( infile, word)) {
cout << "The line is " << word << endl;
ss << word;
while ( getline ( ss, word, ' ' )) {
trailing_char = "space";
cout << "Word: " << word << endl << "Trail: "<< trailing_char << endl;
}
ss.str( string() );
ss.clear();
}
}

代码尝试从文本文件中提取(传递给它的名称),通读它,找到单词(用空格或换行符分隔),然后找出尾随字符(The提到的空格或换行符)

所以这样的文本文件:

abc def ghi

jkl mno pqr

应该有 abc 后跟一个空格,ghi 和 pqr 后跟一个新行(我知道实际上不会,但我将所有内容分配给一个链表以供以后使用,我需要知道那是行尾)。

几个小时以来,我一直试图解开这个谜题,但我已经束手无策了。帮忙?

最佳答案

您首先使用 std::getline(in, word) 读取字符串,这将耗尽所有换行符。当您随后使用 std::getline(in, word, ' ') 时,最后一个单词可能紧跟任何内容,即它位于行边界处。检查换行符和空格之间区别的方法是检查内部 std::getline() 是因为空格还是因为到达字符串末尾而停止,在这种情况下它有效地停止了,因为以下字符是换行符:

while (std::getline( infile, word)) {
std::cout << "The line is '" << word << "'\n";
ss.clear();
ss.str(word);
while (std::getline (ss, word, ' ' )) {
trailing_char = ss.eof()? "newline": "space";
cout << "Word: " << word << endl << "Trail: "<< trailing_char << '\n';
}
}

一种更简单的方法是一次只读取一个单词并打印单词后面的字符是否存在、空格或换行符(或其他空白字符之一):

for (std::string word; infile >> word; ) {
switch (infile.peek()) {
case '\n': trail = "newline"; break;
case '\r': trail = "carriage-return"; break;
case ' ': trail = "space"; break;
case '\f\: trail = "form-feed"; break;
// ...?
default: trail = "end-of-file"; break;
}
std::cout << "word='" << word << "' trail=" << trail << '\n';
}

关于c++ - 判断一个单词后面是否跟有空格或换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18926097/

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