I am participating in few online programming exercises in C++.
Here problem description is given as to test understanding "for" loop in C++.
Input Format
You will be given two positive integers, a and b (a <=b), separated
by a newline.
Output Format
For each integer in the interval [a,b :
If 1 <=n <= 9, then print the English representation of it in
lowercase. That is "one" for , "two" for , and so on. Else if n > 9
and it is an even number, then print "even". Else if n > 9 and it is
an odd number, then print "odd".
Sample Input
8 11
Sample Output
eight
nine
even
odd
I have written program as below and test case passed.
int main() {
int a, b;
cin >> a;
cin >> b;
string num[9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for(int n=a; n<=b;n++)
{
if(n<=9)
cout << num[n-1] << endl;
else
if(n%2==0)
cout << "even\n";
else
cout << "odd\n";
}
return 0;
}
While I am testing, I am entering values for "a" and "b".
I can understand when I submit my code online, test cases are executed and results are shown.
My question how input is automated?. I also want to test my code with automation with out entering input at console.
Sample code for automate will be helpful. This understanding will be helpful as I move forward in working on complex
problems where more inputs will be required, so I don't want to enter manually at cin from console and want to automate this while i am testing at my laptop, just same as the way online automated test tool is doing.
Thanks for your time and help.
Usually, this is achieved through standard file descriptor overrides (which name I came up with on the spot and might be different depending on who's talking).
Considering most online compilers probably run on Linux sessions, they can simply do the following.
Build your single-file solution using (for instance) gcc -o venkysmarty-exo-3
Execute it, but override stdin to be a desired file (e.g. ./venkysmarty-exo-3 < ./test_data/exo-3/input.txt)
More generally, on most unix system and at least while running bash, the > operator can be used to redirect standard output, and < to redirect standard input. If not using file name but opened file/pipe descriptor, prefix the descriptor with & (e.g. python max.py <&64, where 64 is the file descriptor.)
On windows, in batch, the file-descriptor thing probably doesn't work, but basic >, < and >> operators seem to work the same:
So I'll answer your question 2 ways. First way, instead of asking for a value using
cin >> a
you can use
int main(int argc, char *argv[])
as your inputs in Visual Studio and to do that You go to Debug, "project name" properties, and then go to debugging. You should see something called command arguments and you can put whatever input you want in there.
The second way to do "automated" input is to put all of your input values in a file. From there you can open the file and read the values from the file. If you don't know how to read and write to a file I recommend using this link here.
http://www.cplusplus.com/doc/tutorial/files/
This solution is for Visual Studio
Have your input in a text file. On the command line redirect the input from this file.
To specify the input, set up the command line
Get Project > Properties
Under configuration properties, select debugging, then edit Command Arguments
e.g. Test input file at "C:\Projects\test.txt"
Edit command line to read "< C:\Projects\test.txt" (Without quotes
Related
I tried to print a line that asks for input from the user, get the input, then print again some line. The problem is that the white space at the end of the first printed line is printed not at the end of the line, but rather at the beginning of second printed line, after i get the input.
I'm completely new to C++ so I couldn't really try much, but i tried printing the code without the part that prompts the input from the user, and it prints the space just fine, but when i add std::cin << input; the space get's sent to the beginning of the second line.
My code:
int input;
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> input;
std::cout << "Amazing... That's my favorite number too... wow..." << std::endl;
I want the output to be
Enter your favorite number between 1 and 100: //some input
Amazing... That's my favorite number too... wow...
(note the space before //some input)
Instead i get
Enter your favorite number between 1 and 100://some input
Amazing... That's my favorite number too... wow...
(note the space before Amazing)
Edit: I'm using Clion if it could be connected. Also, I tried to run the executable on powershell and it worked as expected, without the problem, so this has something to do with the Clion terminal. Also, i'm using windows 10 as my OS.
Second Edit: add my findings on my answer.
This seems to be a problem with buffered input of Clion. See this issue: https://youtrack.jetbrains.com/issue/CPP-7437
When you are using CLion, You can try disabling PTY (Help | Find Action > type "Registry" > open Registry > find and disable the run.processes.with.pty option)
CLion moving space into new line
Are you sure about that? I tried both in online shell and on local machine and it works as expected.
After checking I found out that this occurs only on the Clion Run terminal, so this has something to do with it exclusively. I'm currently trying to mess around with the settings. I will post a solution and an explanation here if I find it.
Edit: as mentioned in one comment, it could be the issue mentioned here https://youtrack.jetbrains.com/issue/CPP-7437.
In any case it is a Clion related problem exclusively, and not a C++ problem.
This problem is only applicable for the second line, if you leave that line empty then the problem will be fixed. Don't know about C++ but for C before the print statement you have to add: printf("\n");
I'm a newbie to C++ (and to programming in general). I wrote a program that reads and writes staff contact details. This code works well:
// appropriate headers...
int main()
{
char trigger{};
int options = 0;
bool testing{};
fileIps Inptbox; // for entering new data
char ext_title[20]; char ext_intercomNum[4]; char ext_dept[20];
printf("%s", "Enter Officer's Title:\n");
gets_s(ext_title, 20);
printf("%s", "Enter Officer's Intercom Number:\n");
gets_s(ext_intercomNum, 4);
printf("%s", "Enter Officer's Department:\n");
gets_s(ext_dept, 20);
Inptbox.rcv_values(ext_title, ext_intercomNum, ext_dept);
Inptbox.create_string();
testing = Inptbox.validate();
if (testing == true)
return -1;
else if (testing == false)
Inptbox.write_string();
// more code below...
My question is regarding the console output. I had tried to introduce conditional statements to enable selecting a read or write mode. The above code is for writing to file. There are more lines of code below for reading from file and they, too, worked okay.
My challenge is that once I introduce a conditional statement for the above code...
printf("%s", "Enter 1 to WRITE DATA or 2 to READ DATA\n");
cin >> options;
if (options == 1)
{
fileIps Inptbox; // for entering new data
//... rest of code...
}
// more code below...
...the output on the console is flawed, as the prompt for the first entry is displayed but is totally skipped, forcing the user to enter 'Officer's Intercom Number' first. The third prompt worked well.
To elaborate further, when I used cin to assign the value 1 to options (i.e. applying the condition), the console would immediately print...
Enter Officer's Title:
Enter Officer's Intercom Number:
...making it impossible for me to fill in the first entry (i.e. 'Title').
I struggled with this and tried several things to fix it. I used fgets() and even tried it with gets(). I revisited my classes, yet nothing worked. I read widely on things like buffering, studied questions on this site and looked through various resources on cstdio as well as ios_base and its derived classes (which was good because I learned a bunch of other things). However, unless I removed that 'if' statement from my code, nothing I else I tried worked.
So, my question is: "How can this kind of behaviour be explained and how best could I implement my code to enable me toggle between read and write mode?"
I am working with MS Visual Studio 2015.
Using the formatted extraction operator '>>' has its problems. In this case, it reads all values that can convert to an integer. However, you must give an enter to signal that you're ready. The >> operator does not process that newline. When the next time input is read, it sees the previously given newline character. Hence the 'Enter Officer's title' input is immediately set to a newline and continues. Try using something like:
std::string line;
getline(cin, line);
And test the string or convert it.
Ok here's the problem and I'm despaired about it.
I get a 9*9 table using
for (int i=0 ; i < 9 ; i++)
for (int j=0 ; j < 9 ; j++)
cin >> table [i][j];
I want to make some changes to this table . so I get a
command using:
getline (cin , command);
so user would type a command and after parsing it I will make the changes to the table. (it has to be getline() because command is an string and contains spaces)
I have an in.txt containing the table . I give this file to my code using :
g++ main.cpp
./a.out < in.txt .
(these two commands are written in terminal)
after that I want to give my command using keyboard . but the getline() doesn't get anything from keyboard . I tried using
cin.ignore() , cin.clear() , cin.sync () , even cin.get()
but it always passes the getline() .
Any suggestions would be appreciated .
thanks in advance.
Well this is obvious why any input from standard input won't work. This is not limited to getline. operator>> also won't work, nor anything associated with std.cin or stdin.
This is because ./a.out < in.txt is not "giving a txt to a program". It is redirecting the standard input. By default it is a keyboard input from terminal, but you are switching it to a file on a shell level.
If you wanted to switch from terminal associated input to a file, and then backwards, this would be handy: How to redirect cin and cout to files?. Though, in this your case, you will not have the original buffer associated with the terminal, precisely because you make OS not give it to you. You would need to obtain somehow from the system. This would be more complicated (well it would be os specific and less portable) than below suggestions.
I would suggest you to pass the filename as an argument and do not redirect standard input. Or, if you are gonna write some command prompt anyways, make a load_file command, for loading the file. Then load the file using regular means designed for files e.g. ifstream.
First I want to apologist about my bad title. Now the problem. I'm trying to compare two strings in C++. I had try with string.compare and ==, none of them worked. Here is code
if(game_type == "AI vs AI"){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
and with string.compare
if(game_type.compare("AI vs AI") == 0){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
If I give AIvsAI for input the program works correctly, but if i enter AI (space) vs (space) AI, the program prints "Error". I tried using \x20 instant of space but this didn't work too. Any ideas why this is happening?
It appears that you are using a statement similar to
std::cin >> game_type;
to obtain the user input. The problem is that the >> operator only extracts the first word from the line the user types, which makes game_type only contain AI when you type AI vs AI. (As a side note, if you were to use std::cin >> blah on the next line, then blah would contain vs because that typed input had not been consumed yet.)
To fix this, you can use std::getline:
std::getline(std::cin, game_type);
This gets everything the user types on the line (up to but not including the Enter keypress) and puts that in game_type. This is almost always the right way to get user input for an interactive program.
I have this simple code as an example:
#include <iostream>
int main(int argc, const char * argv[]){
int a, b, c;
std::cin >> a >> b >> c ;
std::cout << a << " "<< b << " " << c;
}
I would like to pass this code the arguments "1 2 3" that are in a text file named file.txt located in the same file as main.
In Product > Edit Schemes I select the Run Argument side bar option followed by the arguments tab. Under "arguments passed on launch" I enter < file.txt select ok and run my program. The program builds and runs but does not pass the arguments "1 2 3" in file.txt. Is there some other setting I'm missing? Am I putting my file in the wrong folder? Would really like to make this work so I can test code on large sets of data that would be annoying to enter manually.
if I cout << argv[1] I get "<" if I don't quote. If I do quote the argument I get "< text.txt."
Unfortunately, Xcode doesn't directly support command-line file redirections like you're asking for. The arguments are for setting the argv vector in main. When you run a program on the command line, the shell (typically /bin/bash) interprets and sets up redirections and doesn't pass those bits to the program as arguments. XCode doesn't use a shell to launch your program, and doesn't set up the redirection either.
The closest you can get through Xcode, without changing your source code, requires two steps:
In your scheme's Run setup, in the Info tab, set the executable to /bin/sh. You will need to choose “Other…” from the popup menu to get an Open dialog, then type /bin/sh. When you type / in the Open dialog, you will get a popup text box.
In the Arguments tab, add this argument:
-c "$TARGET_BUILD_DIR/$EXECUTABLE_PATH < /path/to/text.txt"
Replace /path/to/text.txt with the path to your input file.
This will run a shell, and ask the shell to run your program with input redirection, but you will find that Xcode ignores your breakpoints, making it hard to debug your program.