简体   繁体   English

在字符串上使用 getline

[英]Using getline on a string

How can I use getline() to read words form a line that I have stored in a string?如何使用getline()从存储在字符串中的一行读取单词?

For example:例如:

char ch[100],w[20];
cin.getline(ch,100);

Now can I use getline to count the number of words in ch ?现在我可以使用getline来计算ch的单词数吗? I don't want to use a delimiter to directly count words from ch .我不想使用分隔符直接从ch计算单词。 I want to read words from ch and store them in w .我想从ch读取单词并将它们存储在w

I have tried using ch in getline as a parameter.我曾尝试在getline使用ch作为参数。

getline is implemented in the standard as either a stream method , or a string method which takes a stream: http://en.cppreference.com/w/cpp/string/basic_string/getline getline在标准中作为流方法或采用流的string方法实现: http : //en.cppreference.com/w/cpp/string/basic_string/getline

There is no standard implementation of getline which does not require a stream.没有不需要流的getline标准实现。

That said you can use ch to seed a istringstream to count the words in the string, but basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>&& input, basic_string<CharT, Traits, Allocator>& str) assumes a newline as the delimiter so that's not what you're going to want to count words.也就是说,您可以使用chistringstream设置种子以计算字符串中的单词数,但basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>&& input, basic_string<CharT, Traits, Allocator>& str)假设一个换行符作为分隔符,因此这不是您想要计算单词的内容。 Similarly, a getline that takes a delimiter will only break on a specific character.同样,带有分隔符的getline只会在特定字符上中断。 Instead you could usebasic_istream& basic_istream::operator>> which will split words on all whitespace characters:相反,您可以使用basic_istream& basic_istream::operator>>它将在所有空白字符上拆分单词:

istringstream foo(ch);

for(auto i = 1; foo >> w; ++i) {
    cout << i << ": " << w << endl;
}

Live Example现场示例


Just as a note here, defining char w[20] is just begging for an out of bounds write.就像这里的注释一样,定义char w[20]只是乞求越界写入。 At a minimum you need to define that such that if ch is filled with non-whitespace characters, w can contain it all.您至少需要这样定义,如果ch填充了非空白字符,则w可以包含所有内容。 You could do that by defining char w[100] .您可以通过定义char w[100]来做到这一点。
But if someone were to come and increase the size of ch without changing the size of w and then you'd be in trouble again.但是如果有人来增加ch的大小而不改变w的大小,那么你又会遇到麻烦。 In C++17 you could define w like this char w[size(ch)] prior to that you could do char w[sizeof(ch) / sizeof(ch[0])]在 C++17 中,你可以像这样定义w char w[size(ch)]之前你可以做char w[sizeof(ch) / sizeof(ch[0])]
But your best option is probably to just make both w and ch string s so they can dynamically resize to accommodate user input.但是您最好的选择可能是同时制作wch string以便它们可以动态调整大小以适应用户输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM