有关替换字符的代码问题


代码用来使用“,”替换空格。

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void main() {
    string file_path = "test.txt";//文件路径
    string out_path = "ttttt.txt";//输出路径
    string str;
    string::size_type pos = 0;
    ifstream instream;
    ofstream outstream;
    instream.open(file_path);
    if (!instream)
        cout << "error" << endl;
    outstream.open(out_path);
    while (getline(instream,str)) {
        pos = str.find(" ");//查找字符在string中第一次出现的位置
        while (pos != string::npos)//判断是否存在“hyu”这个字符
        {
            str.replace(pos, 1, ",");//用,替换 .
            
            pos = str.find(" ", pos + 1);//查找剩余字符串
        }
        outstream << str << endl;

    }
    instream.close();
    outstream.close();
    system("pause");

}

 此代码可行。

接下来的代码则不可行。

void main() {
	
	string str=" ";
	string line;
	string::size_type pos = 0;
	string target=",";
	ifstream instream;
	ofstream outstream;
	instream.open("test.txt");
	outstream.open("ttttt.txt");
	while (getline(instream, line)) {
		pos = str.find(str);//查找字符在string中第一次出现的位置
				while (pos != string::npos)// 判断有没找到
		{
			line.replace(pos, str.size(), target);//替换字符串
			pos = line.find(str, pos + 1);//查找剩余匹配字符

		}
			
			outstream << str << endl;
		
	}
	instream.close();
	outstream.close();

 这一段代码 会导致死循环 ,原因 个人猜测可能是应为空格符比较特殊的原因。

posted @ 2017-08-27 00:30  Zerozzx  阅读(229)  评论(0编辑  收藏  举报