Ryan Sanchez
Ryan Sanchez

Reputation: 1

How to append character values from a character array

I am trying to create a function which takes a line of input, and creates a string for each number in the input. Then it needs to find the largest number out of the strings created.

For instance, if the line was "12.50 13 14.50 14", I would need the function to create strings with the values of "12.50", "13", "14.50", and "14", and then return "14.50" but as a string. As the code runs currently, it will iterate through each character in the sentence, and correctly set the value of "ch" to the character of the input line in question. I cannot get the code to properly append the ch values to the new number. Number begins as an empty string and the line number.append(1,ch) appends nothing for each iteration of the code.

int cnt_space(int i, int count, char ch,string sentence1)
{
 
    // input sentence
    
    ch = sentence1[0];
 
    // counting spaces
    int greatest = 0;
    while (ch != '\0') {
        ch = sentence1[i];
        string number;
        
        if (isspace(ch))
            count++;
            cout << "number: " << number << endl;
        cout << "ch: " << ch << endl;
        number.append(1,ch);
        
       // if (number >= greatest)
       //     greatest = number;
 
        i++;
    }
    return count;
}

Upvotes: 0

Views: 125

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57678

Here's a solution based on my understanding of your requirements:

std::string Max_Number_As_String(const std::string& text)
{
    std::istringstream  text_stream(text);
    double max_value = 0.0;
    double value;
    while (text_stream >> value)
    {
        if (value > max_value) max_value = value;
    }
    std::string value_as_string = std::to_string(max_value);
    return value_as_string;
}

The above code converts the input string to a stream, then uses operator>> to read the numbers for the string. A running maxima is maintained. After all the numbers are read, the maxima is converted to a string and returned.

Upvotes: 2

Related Questions