Home > OS >  When I attempt to add a specific character of a string through push_back() it throws me a type conve
When I attempt to add a specific character of a string through push_back() it throws me a type conve

Time:04-17

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    string input;
    getline(cin, input);
    int x = input.length();
    vector<string> arr;
    for(x; x==0; x-2){
        arr.push_back(input[x]);
    }

    return 0;
}

I get the following error when I try to compile:

simplearraysum.cpp:16:23: error: reference to type 'const std::__vector_base<std::string, std::allocator<std::string> >::value_type' (aka 'const std::string') could not bind to an lvalue of type 'std::basic_string<char>::value_type' (aka 'char')

arr.push_back(input[x]);

Could anyone offer some advice on what I could do?

CodePudding user response:

There are several bugs in the code that make it fail; most important the third part of the for loop: x-2 calculates the result of the subtraction, and then moves on. It is never stored anywhere, so x never changes. The loop runs forever, inserting over and over input[x] into the vector, until something blows up. You probably mean to use: x = x-2.

Second problem is if x is odd - subtracting 2 will never hit exactly zero, so the loop will again never stop. You should use x>=0 or such for the condition.

Third, input[x] is a char, not a string; the vector expects strings. That is what the shown error message talks about.

Fourth, if x is the length of the string, input[x] accesses the char behind the string - in C and C , indices start with 0, so an array of x chars goes from arr[0] to arr[x-1].

  • Related