从函数返回字符串导致格式问题

时间:2014-04-07 03:45:12

标签: c++ arrays string loops

它应该是这样的:http://i.imgur.com/gko501E.png

相反,它看起来像这样:http://i.imgur.com/ISwqyD8.png

当我从函数中取出代码并在主类中使用它时,它可以正常工作。但是,一旦我把它放在这个函数中就会出现格式化问题,它也不会像它应该的那样进行过滤。该程序应该接受用户输入,将其存储在字符串中,删除所有非字母字符,大写元组,然后根据命令行中给出的用户定义变量将其分隔出来。它还应该在命令行中接受文件作为输入,例如:'program 5 8<文件”。

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <cstdlib>
#include <fstream>
#include <sstream>

using namespace std;

//make vowels uppercase
string filter(string input)
{
    size_t found = input.find_first_of("aeiou");

    while (found != string::npos)
    {
        if (islower(input[found]))
        {
            input[found] = toupper(input[found]);
            found = input.find_first_of("aeiou", found + 1);
        }
    }

    //Make consonants lowercase

    size_t foundLower = input.find_first_of("BCDFGHJKLMNPQRSTVWXYZ");

    while (foundLower != string::npos)
    {
        if (isupper(input[foundLower]))
        {
            input[foundLower] = tolower(input[foundLower]);
            foundLower = input.find_first_of("BCDFGHJKLMNPQRSTVWXYZ", foundLower + 1);
        }
    }

    //remove punctuation
    for (int i = 0, len = input.size(); i < len; i++)
    {
        if (!isalnum(input[i]))
        {
            input.erase(i--, 1);
            len = input.size();
        }
    }

    return input;
}

int main(int argc, char* argv[])
{
    int wordSize;
    int wordSizeCounter;
    int wordCounter = 0;
    int rowSize;
    //char letter;

    wordSize = atoi(argv[1]);
    rowSize = atoi(argv[2]);

    ifstream inFile;
    inFile.open(argv[3]);//open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();//read the file
    string test = strStream.str();//str holds the content of the file
    if (!inFile) test = cin.get() ;             //   Read first character



    //Begin filter for files

    while (!test.empty())
    {
        filter(test);

        if (test.length() < wordSize) //make sure we don't go out-of-bounds
        {
            wordSize = test.length();
        }

        cout << test.substr(0, wordSize);
        cout << " ";

        if (test.length() >= wordSize) //again, make sure we don't go out-of-bounds
        {
            test = test.substr(wordSize);
        }
        else
        {
            test = " ";
        }

        wordCounter++;
        if (wordCounter == rowSize)
        {
            cout << std::endl;
            wordCounter = 0;
        }

        if(test.empty())
        {
            test = cin.get();
        }
    }


    cout << endl;
    return 0;
}

0 个答案:

没有答案