How do I take a vector input using command line argument? - c++

I am not familiar with using command line arguments. I am trying to take a vector input as a command line argument. Please refer the below code and help me with the error.
#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main(int argc, char *argv[]){
vector<int> arr;
cout<<"Arguments are:\n";
for(int i = 1 ; i < argc ; i++){
arr.push_back(argv[i]);
}
for(int i = 0 ; i < arr.size() ; i++){
cout<<arr[i]<<" ";
}
}
The code is giving below error.

The problem is, that your vector contains ints, but the command line arguments are strings (see error).
You should convert the argv[i] to int, than use the push_back().
You can use stoi() which converts string to int, but keep in mind that it could happen when not just digits appear in the command line argument.

Related

Reverse of an array Hackerrank

This is a syntax of a program that I made of hackerrank to reverse an array. The location of the question is Practice < Data Structures < Arrays < Arrays - DS
the program seems to work fine on an online compiler but is showing error over hackerrank.
can anyone guide me where I went wrong?
#include<iostream>
using namespace std;
int main(){
int n,i;
int arr[n];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
You are creating an array with n elements before you read n, i.e n is having garbage value. Here is correct working code.
#include <iostream>
using namespace std;
int main(){
int n,i;
cout<<"Enter number of elements"<<endl; // Comment it if you don't want debug console outut
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements"<<endl; // Comment it if you don't want debug console outut
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
I changed your solution and it work fine now , i will tell you some notes for your future:
1 - You have to read size of array first before declare array as mentioned in comments by #HolyBlackCat , otherwise it will give garbage value.
2 - this command int arr[n]; won't work on all Compilers and may give you an Error. Is there a solution to declare array without specific size ? Yes , you can use Vector like that vector<int> arr(n);but you have to include library of vector first #include<vector>
3 - In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. On most operating systems returning 0 is a success status like saying "The program worked fine". So you have to write return 0; in the end of your program.
#include<iostream>
#include<vector> // must include to use Vectors
using namespace std;
int main(){
int n;
cin >> n; // Must read size of array first , otherwise it will give it garbude value
vector<int> arr(n); // instead of int arr[n]
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
for(int i = n-1 ; i >= 0 ; i--)
cout << arr[i] << " ";
cout << endl; // to print new line as mentioned in the problem statement
return 0; // Prefer to use it always
}
Hope that helps you and Good Luck.
The exercise of Hacker Rank needs that you reverse an array of integers, might you have a problem with the variable size array, cause some compilers support this characteristic but others not.
And Hacker Rank do not support some properties in other languages like JS , Hacker Rank do not support prompt() for take an input.
In any case for fix this error you can use vector class.
#include<iostream>
#include<vector>//Include library vector for dynamic size of array
using namespace std;
int main(){
int n;
cin>>n;
vector<int> arr(n);//Declare the vector with a max size n
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i = n-1 ;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
This code has passed al test cases of hackerRank
All the test on hackerRank had passed

C++: "Multi-character character constant" warning when reading from a file into char array

#include <fstream>
#include <iostream>
using namespace std;
int main(){
ifstream input;
input.open("kr.txt");
int n;
input >> n;
for(int i = 0; i < n; i++){
char line[16];
input.ignore(256, '/n');
input.get(eil, 16);
}
return 0;
}
I get the warning at the "input.ignore()".
My file looks like this. 15 spaces separate the beginning of the line to the first number.
2
Rimas 195.5 45
Robertas 165 13
/n is constant consisting of two chars, '/' and 'n'and you are not quoting it as a string, using ", but as a char, using ', hence warning.
Maybe you wanted to use backslash instead of slash, i.e. '\n'?

reversing input - undefined output

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main(){
char zahl[255];
cin>>zahl;
for(int i=255; i>=0; i--)
if(zahl[i] != 0)
cout<<zahl[i];
cout<<endl;
return 0;
}
When I enter some words the input gets reversed but before and after that there are undefined expressions. Can someone explain the reason for this?
As far as I understood, the char array is filled with the inserted expression (from [0] on), the rest is filled with '\0's. By the if condition I skip the '\0's. Where do the undefined expressions come from?
ty
greets CS
Initially, the array is uninitialised and contains garbage. cin writes the input followed by a single zero to terminate; the rest of the array still contains garbage, which your loop outputs before the input.
You could specify that the array be zero-initialised:
char zahl[255] = {};
Or you could measure the string length, and start from there:
for (int i=std::strlen(zahl)-1; i >= 0; i--)
Or, better still, use the standard library to fix the potential buffer overrun:
std::string zahl;
std::cin >> zahl;
std::copy(zahl.rbegin(), zahl.rend(), std::ostream_iterator<char>(std::cout));
Your for loop will run 256 times, assuming that the word entered is 255 characters long. However, user input will vary in length, so instead calculate the length and use it in the for loop.
int len = strlen(zahl);
The code will now be:
#include <iostream>
#include<string.h>
using std::cout;
using std::cin;
using std::endl;
int main(){
char zahl[255];
cin>>zahl;
int len = strlen(zahl);
for(int i=len-1; i>=0; i--)
if(zahl[i] != 0)
cout<<zahl[i];
cout<<endl;
return 0;
}

c++ Replacing character with a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this code. What i wanted to do is to replace every letter from every char with indicated number. Like for A is 10, and so on until J, 19. My code works well if i have only one letter in my char array, but if i have more after another it copies useless things. I think that something is wrong with strncat.
#include<conio.h>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char litera[11]={"ABCDEFGHIJ"};
char cifra[11]={"0123456789"};
char rezultat[256]={0};
int n;cin>>n;cin.get();
for(int i=0;i<n;i++)
{
char x[256];
cin.get(x,256);cin.get();
int k=strlen(x);
for(int j=0;j<k;j++)
{
int p = strchr(litera,x[j])-litera;
if(p>=0 )
{
strncat(rezultat, x,j);
// my p is the indicator for letter and number
strcat(rezultat,"1");
// I'm copying an 1 there because i have numbers
// between 10-19 and in my int array i have only
// the second cipher
strcpy(x,x+j);
rezultat[strlen(rezultat)]=cifra[p];
}
}
cout<<rezultat<<endl;
memset(rezultat,0,sizeof(rezultat));
}
getch();
return 0;
}
Input: 07B, 1AA, C8A
Output: 0711, 11010, 12810
My output:
0711
110AA1
12C810
If you guys can tell me where the problem is, you'll help me a lot, every suggestion is well received, even if is not about this problem. Thanks!
If it is allowed to use vector and string then you can try the following (I tested it and it works.) The input here should be line by line(each line is a new string to be converted) but of course you may modify this part based on your input format:
Include those:
#include <vector>
#include <iostream>
#include <string>
//#include <conio.h>
//#include <cstring>
//using namespace std;
int main()
{
int n;
std::cin >> n;
while (n--)
{
string input;
std::cin >> input;
vector<char> resultat;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J') // it is a letter between A and J
{
int number = input.at(i) - 'A' + 10;
char ones = (char)(((int)'0') + (number % 10));
char tens = (char)(((int)'0') + (number / 10));
resultat.push_back(tens);
resultat.push_back(ones);
}
else
resultat.push_back(input.at(i));
}
for (int i = 0; i < resultat.size(); i++)
{
std::cout << resultat[i];
}
std::cout << endl;
}
}
if string is not allowed just use your character array. There seems to be nothing wrong in your input format.
If vector is not allowed either, then you may create a char pointer the initialize it based on the final size.
For example:
int newSize=0;
for (int i = 0; i < input.size(); i++)
{
if (input.at(i) >= 'A' && input.at(i) <= 'J')
newSize+=2;
else
newSize++;
}
char* resultat = new char[newSize];
...
Then just fill the resultat.
Hope that helps!
Do you have to do it with your multiple arrays? You could perform a switch-case for only specified inputs. Since you are replacing letters A-J with numbers 10-19, you can easily implement this in switch case. You can also check for incorrect input as well.
If you have to use arrays, first question is why is you numerical array the single digits? Is this is constraint? Cant you use :
char cifra[11]={"10","11","12","13","14","15","16","17","18","19"};
for the array instead, that way you can refer to the array index and replace it using the index? This way, you can compliment the arrays by just using index referencing to replace the output based on the index, such as A is index 1 for alphabetical array which refers to index 1 of the numerical array which is "10" so you just print the array index value to a variable and output it.

Reformatting an entered string with spaces in it

Currently I am working on a problem to reformat the inputted string into the odd char then even char with no newline. ex. Input: Good Test. Ouput: Go etodTs. For some reason when I run the program it only outputs a "G".
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main (int argc, char ** argv) {
char sWordOdd[100] = {0};
scanf("%s", sWordOdd);
int iNum = strlen(sWordOdd);
for (int i=0; i<=iNum && i%2==0; i++) {
printf("%c",sWordOdd[i]);
}
for (int a=0; a<=iNum && a%2!=0; a++) {
printf("%c",sWordOdd[a]);
}
printf("\n");
return 0;
}
Your i<=iNum && i%2==0 break condition terminates your loop early. To achieve the effect you want, put an if statement inside the loop, like so:
for (int i = 0; i <= iNum; i++){
if(i % 2 == 0)
printf("%c",sWordOdd[i]);
}
As for your second loop, I think you meant a++ instead of a--, because otherwise you'll try to access the array using a negative index. I think you meant for your loop to look like this:
for (int a = 0; a <= iNum; a++){
if(a % 2 != 0)
printf("%c",sWordOdd[a]);
}
Side note: Notice the spacing between the variables and the operators in my code. Using spaces like this makes your code easier to read.
int main()
{
string line;
getline(cin, line);
for (size_t start : {0,1})
for (size_t ii = start; ii < line.size(); ii += 2)
cout << line[ii];
cout << endl;
}
The above code handles arbitrarily long lines, is C++11 rather than C, and works.
As said before the loops terminate if i<=iNum && i%2==0 is true (for the first loop), which is the case for i=0. The second loop terminates with i=1.
Since you want to iterate all characters you have to move the i%2==0 part out of the for-statement:
for (int i=0; i<=iNum; i++) {
if (i%2==0)
{
printf("%c",sWordOdd[i]);
}
}
The second loop needs to be modified in the same way...
To fix this problem you have to use a function that can see stuff after whitespaces. This function is called getline. But with getline, you have to use string, so in this example I used string. I then found the size with the .size() function and then using just one constraint for the for loop instead of two in the question. I also took off the char array and replaced it with string as stated above. Everything else is pretty much the same. Using this answer lets me not having to use cstring and also simplifying my code into a short, easy way that is easy to follow through.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
using namespace std;
int main (int argc, char ** argv)
{
string sWordOdd;
getline(cin, sWordOdd, '\n');
int iNum = (int)sWordOdd.size();
for (int i=0; i<iNum; i+=2){
cout << sWordOdd[i];
}
for (int a=1; a<iNum; a+=2){
cout << sWordOdd[a];
}
printf("\n");
return 0;
}