关键词搜索

源码搜索 ×
×

find 函数和string :: npos 的用法

发布2013-10-25浏览17981次

详情内容

      设1.txt文件内容如下:

name = baidu
url = www.baidu.com

 

       看程序:

  1. #include <fstream>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. ifstream in("1.txt");
  8. string filename;
  9. string line;
  10. string s;
  11. string :: size_type pos;
  12. if(in) // 有该文件
  13. {
  14. while (getline (in, line)) // line中不包括每行的换行符
  15. {
  16. pos = line.find("name");
  17. if(pos != string :: npos)
  18. {
  19. s = line.substr(pos + strlen("name") + strlen(" = "));
  20. cout << s.c_str() << endl;
  21. }
  22. pos = line.find("url");
  23. if(line.find("url") != string :: npos)
  24. {
  25. s = line.substr(pos + strlen("url") + strlen(" = "));
  26. cout << s.c_str() << endl;
  27. }
  28. }
  29. }
  30. else // 没有该文件
  31. {
  32. cout <<"no such file" << endl;
  33. }
  34. return 0;
  35. }

     结果为:

baidu

www.baidu.com

 

    当然也可以用sscanf, 如下:

  1. #include <fstream>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7. ifstream in("1.txt");
  8. string filename;
  9. string line;
  10. char s1[1024] = {0};
  11. char s2[1024] = {0};
  12. if(in) // 有该文件
  13. {
  14. while (getline (in, line)) // line中不包括每行的换行符
  15. {
  16. if(2 == sscanf(line.c_str(), "%s = %s", s1, s2))
  17. {
  18. cout << s2 << endl;
  19. }
  20. else
  21. {
  22. return 1;
  23. }
  24. }
  25. }
  26. else // 没有该文件
  27. {
  28. cout <<"no such file" << endl;
  29. }
  30. return 0;
  31. }


 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载