Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ argv[] not being passed fully

Tags:

c++

arguments

// Type the determine year in the command line as an argument.
// This program then prints the months and days for that year.

//Known Error argv[1] = the first digit of year,

#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

void printYear(int year);

int _tmain(int argc, char *argv[]){ 
    string str;//varible used to exit the program

    if (argc == 1 ){//checks to see if the years were inputted corrected
        std::cout << "Please input Year in the command line. Exiting.." << std::endl;
        cout << "Please type anything to continue..." << endl;
        cin >> str;
        return 1;
    }

    int Year = 1982;
    int numYears = argc-1;

    cout << "Number of Argments Loaded : " << numYears << endl;
    for (int x = 1; x <= numYears; x++){
        Year = atoi(argv[x]);
        cout << "Year : " << argv[x] << endl;
        cout << "Year is " << Year << endl;
        printYear(Year);
    }

    cout << "Please type anything to continue..." << endl;
    cin >> str;
    return 0;
}

I'm currently learning C++ and this is one of my assignments. I just spent a better half of a day looking into this to no avail.

printYear() has been tested with numerous years and is functional. The only remanding error left is with argv[]. It only returns the first digit of the year inputted, which is fine if you want to research years 0-9. Any tips or trick you guys mind passing me? (I'm using Microsoft Visual Studio fyi)

Command line

calender.exe 1982

returns with

Number of Arguments Loaded : 1
Year : 1
Year is 1

Repetitive code I know but I'm troubleshooting.

like image 435
Code Eyez Avatar asked Jun 03 '14 18:06

Code Eyez


2 Answers

The problem is _tmain. If you have unicode enabled it tries to give you wide (UTF-16) characters, so every other character will be \0. To fix this you want to call it main instead.

like image 115
Dan Avatar answered Sep 22 '22 19:09

Dan


It seems that the arguments are passed as UNICODE strings however you process them in the program as ASCII strings.

like image 21
Vlad from Moscow Avatar answered Sep 26 '22 19:09

Vlad from Moscow