[英]C++ How to read two lines from string to separate strings?
I got a string foo with 2 lines: 我有两行的字符串foo:
string foo = "abc \n def";
How I can read this 2 lines from string foo: first line to string a1 and 2th line to string a2? 我如何从字符串foo读取这2行:第一行到字符串a1,第二行到字符串a2? I need in finish: string a1 = "abc";
我需要完成:字符串a1 =“ abc”; string a2 = "def";
字符串a2 =“ def”;
Use string stream: 使用字符串流:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string foo = "abc \n def";
std::stringstream foostream(foo);
std::string line1;
std::getline(foostream,line1);
std::string line2;
std::getline(foostream,line2);
std::cout << "L1: " << line1 << "\n"
<< "L2: " << line2 << "\n";
}
Check this link for how to read lines and then split the line into words: 检查此链接以了解如何阅读行,然后将行拆分为单词:
C++ print out limit number of words C ++打印出字数限制
You could probably read it into a string stream, and from the stream output both words into separate strings. 您可能将其读入字符串流,然后从该流中将两个单词输出为单独的字符串。
http://www.cplusplus.com/reference/iostream/stringstream/stringstream/ http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
This seems like the easiest solution for me, though the stringstream way works too. 这对我来说似乎是最简单的解决方案,尽管stringstream方法也可以。
See: http://www.sgi.com/tech/stl/find.html 请参阅: http : //www.sgi.com/tech/stl/find.html
std::string::const_iterator nl = std::find( foo.begin(), foo.end(), '\n' ) ;
std::string line1( foo.begin(), nl ) ;
if ( nl != foo.end() ) ++nl ;
std::string line2( nl, foo.end() ) ;
Then just trim the lines: 然后修剪线条:
std::string trim( std::string const & str ) {
size_t start = str.find_first_of( " " ) ;
if ( start == std::string::npos ) start = 0 ;
size_t end = str.find_last_of( " " ) ;
if ( end == std::string::npos ) end = str.size() ;
return std::string( str.begin()+start, str.begin()+end ) ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.