zoukankan      html  css  js  c++  java
  • 有关替换字符的代码问题


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

    #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();
    

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

  • 相关阅读:
    cUBtYhaFzo
    「UVA1185」Big Number 解题报告
    「洛谷P3202」[HNOI2010]弹飞绵羊 解题报告
    「洛谷P2906」[USACO08OPEN]牛的街区Cow Neighborhoods 解题报告
    「洛谷P1306」斐波那契公约数 解题报告
    「SP25784」BUBBLESORT
    「UVA12004」 Bubble Sort 解题报告
    「洛谷P2397」 yyy loves Maths VI (mode) 解题报告
    「学习笔记」珂朵莉树 ODT
    log4j
  • 原文地址:https://www.cnblogs.com/Zerozzx/p/7436901.html
Copyright © 2011-2022 走看看