Don Larynx
Don Larynx

Reputation: 695

Why does adding two spaces produce incorrect output?

I have the following program meant to calculate primes:

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

bool primeTest(int number){
    if ((number == 0) || (number == 1)){
        return false;
    }
    if ((number == 2) || (number == 3)){
        return true;
    }
    for (int j = 2; j <= number / 2; j++){
        if (number%j == 0){
            return false;
        }
    }
    return true;
}

int main(){
    vector<int> primeVector;
    for (int i = 0; i <= 100; i++){
        if (primeTest(i)){
            primeVector.push_back(i);
        }
    }
    int pvSize = primeVector.size();
    for (int i = 0; i < pvSize; i++){
        cout << primeVector[i] << ' ';
    }
    cin.get();
}

If I change the line cout << primeVector[i] << ' '; to cout << primeVector[i] << ' '; (I added a space) it gives me

28224382245822478224118224138224178224198224238224298224318224378224418224438224
478224538224598224618224678224718224738224798224838224898224978224

instead of

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Why does this occur? Only a space was added. It doesn't occur with double quotes.

Upvotes: 0

Views: 62

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57743

Simply put, one space is one characer, two spaces is two characters or a C-Style string.
' ' -- single character.
" " -- two spaces require double quotes.

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119382

String literals should be enclosed in double quotes, not single quotes. Single quotes are used for character literals. If you have multiple characters in a single character literal, the value is some implementation-defined integer. Multi-character literals are rarely useful.

(Note that this doesn't apply to something like '\n', which is a single character represented by an escape sequence.)

Use " " instead.

Upvotes: 4

Related Questions