0

Here is my code I dont know why its taking two times input from me for vectors?

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    cin>>s;
    vector<int> v;
    int len=sizeof(s);
    for(int i=0;i<len;i++){
        int a;
        cin>>a;
        v.push_back(a);
    }
    int cost=0;
    for(int i=1;i<sizeof(s);i++){
        if(s[i-1]==s[i]){
            cost+=min(v[i-1],v[i]);
        }
    }
     return 0;
}

Input(Expected):

abaac
1 2 3 4 5

Input(Real):

abaac
1 2 3 4 5
1 2 3 4 5
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
DrkEthics
  • 1
  • 1
  • The `sizeof` an object is independent of its contents. The `sizeof` an instance of `std::string` doesn't change with the value of the string. In particular, it does not return the length of the value of the string, it returns the amount of space the object itself occupies. – David Schwartz Sep 06 '20 at 03:37

3 Answers3

2

To get the length of a string, use s.size(), not sizeof.

For more information about sizeof, see Why is sizeof(std::string) only eight bytes?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

my friend. If you can not figure out why, you could add a code

cout << len << endl; after you input"abaac",

and you can find the value of "len" are 28, but not 5 that you're expected. The right way to know the length of String is to use "String.size()"

Ricky_Lab
  • 21
  • 5
0

Use s.size() for getting the size of vector and then loop through it to get the input.
sizeof() is used to determine the size of a data-type or variable in bytes.

Aditya_
  • 1
  • 1