0

I'm trying to take in some input and find the number of a certain character in a string. I keep getting a weird answer when I try to take in the actual string. Why is this happening? I'm using cout to find why I'm getting such weird numbers and it appears to be a problem with the input.

Note - This is my attempted solution to Codeforces Problem 462 B. I'm attempting to just find the number of a certain letter in the input. My friend is attempting a bubble sort method.

Input:

6 4
YJSNPI

Expected Output:

YJSNPI
4

Actual Output:

YJSNPI
1699623981

Code:

#include <iostream>
#include <string>
#include <vector>
#include <istream>

using namespace std;

int main()
{
    int n, k, counting;
    cin >> n >>k;
    char trash;
    cin.get(trash);
    vector<string> cards;
    string theline, name;
    cin >> theline;
    cout << theline << "\n";
    for (int i = 0; i < n; i++){
        name = theline[i];
        cards.push_back(name);
    }
    for (int i = 0; i < n; i++){
        if (cards[i] == cards[k-1]){
            counting++;
        }
    }
    int tmp = 0;
    if (cards.size() != k){
        tmp = k - counting;
    }
    counting *= k;
    counting += tmp;
    cout << counting;
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
user44726
  • 9
  • 1

3 Answers3

4

Local variables are not automatically initialized to 0. If you try to use the value of a local variable before assigning it, you get undefined behavior. You're incrementing counting without ever initializing it. Change to:

int n, k, counting = 0;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • The code works now. I'm not getting the right answer but that's more a problem with my solution than anything else. Thanks. – user44726 Aug 29 '14 at 00:14
3

The issue is that the variable "counting" is never initialized - handy link

Basically, "counting" has some garbage value from memory after you declare it with

int counting;

Then, the first operation performed is

counting++;

And the garbage value is saved.

THE FIX:

Change

int counting;

to

int counting = 0;

NOTE: n and k are not helpful variable names. It would make understanding the code a lot easier if they had real names, but oh well.

ADDITIONALLY: As chris mentioned above, make the compiler work for you. See comment below for good compiler flags. Don't ignore warnings!

Community
  • 1
  • 1
Vlad274
  • 6,514
  • 2
  • 32
  • 44
0

Can't really understand what you are doing here. But I can see where you are going wrong.

int n, k, counting;

counting is uninitialized try

int n, k, counting = 0;

I get answer of (1*4 + 4 - 1) = 7 not the 4 you are expecting.

This code will always result in counting = 1, given that k is within range.

for (int i = 0; i < n; i++){
    if (cards[i] == cards[k-1]){
        counting++;
    }
}

https://ideone.com/7Hk3ix

difftator
  • 23
  • 3