C++ printing spaces or tabs given a user input integer - c++

I need to turn user input (a number) into an output of TAB spaces.
Example I ask user:
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
the (n) i need to turn it into an output like:
cout << n , endl;
and what prints on the screen would be the spaces
ex
input is 5
out put |_| <~~~there are five spaces there.
Sorry If I can't be clear, probably this is the reason I haven't been able to find an answer looking through other people's questions.
any help will be greatly appreciated.

Just use std::string:
std::cout << std::string( n, ' ' );
In many cases, however, depending on what comes next, is may be
simpler to just add n to the parameter to an std::setw.

cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
cout << " " ;
}
cout <<endl;

You just need a loop that iterates the number of times given by n and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}

I just happened to look for something similar and came up with this:
std::cout << std::setfill(' ') << std::setw(n) << ' ';

You can use C++ manipulator setw(n) function which stands for set width to print n spaces.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
std::cin>>n;
cout<<"Here is "<<n <<" spaces "<<setw(n)<<":";
}
And don't forget to include C++ Library -
enter image description here

Appending single space to output file with stream variable.
// declare output file stream varaible and open file
ofstream fout;
fout.open("flux_capacitor.txt");
fout << var << " ";

Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";

Related

NOTE:(getline was not the issue) C++ getline() stops working in user defined function but works in main function

NOTE: SOLVED, problem was not getline() but find function with an
Improperly filled array!
I've looked up several questions before posting my own, but I could not find an answer for my problem. This is my first question posted, but I did do some research and tried other solutions from other questions before posting my own. So I am not entirely sure this isn't a duplicate. My apologies! Thank you for understanding in advance!
I am trying to use getline() (c++) to get user input. It works fine in my main, but does not in my user defined function. I thought it might have to do with the buffer, so i used cin.ignore() as suggested in:
C++ getline method not working
and i checked:
How does getline work with cin?
to make sure I properly understood getline(). However my program still does not work correctly.
My program takes English Text as a string from user input (console input) and converts it into Morse Code and outputs result as a string (console output).
basically my problem is this:
getline works in my main function for both strings and strings with spaces ex: "This" and "This Code".
However, in my user defined function, it ONLY works for strings without spaces ex: "This".
Thanks for the help! Code snippets below!
#include <iostream>;
#include <stdio.h>;
#include <ctype.h>;
using namespace std;
string textToMorse(const string alphabet, const string morseAlphabet[]);
int main()
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?";
const string morseAlphabet[39] = {".-","-...","-.-.","-..",".","..-.","--.","....","
..",".---","-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---",
"...--","....-",".....",
"-....","--...","---..","----.",".-.-.-","--..--","..--.."};
int userSelection;
string resultString;
cout << "TEXT TO MORSE CODE or MORSE CODE TO TEXT program" << endl << endl;
cout << "Please select an option by typing the integer shown: " << endl << endl;
cout << "Type(Selects option) 1 to decode Morse code to English text" << endl;
cout << "Type(Selects option) 2 to encode English text to Morse code" << endl;
cout << "Type(Select option) any other integer that is NOT 1 or 2 to QUIT" << endl << endl;
cin >> userSelection;
while(userSelection == 1 || userSelection == 2)
{
if(userSelection == 1)
{
resultString = textToMorse(alphabet, morseAlphabet); // function where I use
// getline() but does not work
cout << endl << "This is the Morse code decoded to English text: " << endl << endl;
cout << resultString << endl << endl << endl << endl;
}
}
return 0;
}
// does not work
string textToMorse(const string alphabet, const string morseAlphabet[])
{
string userInput;
cout << endl << "Enter English text to encode to Morse code,
with only a space between words: " << endl << endl;
cin.ignore();
getline(cin,userInput); //code works with strings without spaces,
//but breaks with others. ex: "This" works as input
//but "This code" breaks and the console seems to freeze
// then crashes out
cin.clear();
// rest of code, but program breaks before this.
string encodedEnglishText = "";
for(int i = 0; i < userInput.length(); i++)
{
userInput[i] = toupper(userInput[i]);
}
for(int i = 0; i < userInput.length(); i++)
{
encodedEnglishText += morseAlphabet[alphabet.find(userInput[i])];
encodedEnglishText += " "; // extra spacing added for output clarity
if(userInput[i] == ' ')
{
encodedEnglishText += " "; // extra spacing added for output clarity
}
}
return encodedEnglishText;
}
However if I edit my code and get the input from my main and pass it in as a parameter, it works.
#include <iostream>;
#include <stdio.h>;
#include <ctype.h>;
using namespace std;
string textToMorse(const string alphabet, const string morseAlphabet[], string userInput);
int main()
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?";
const string morseAlphabet[39] = {".-","-...","-.-.","-..",".","..-.","--.","....","
..",".---","-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---",
"...--","....-",".....",
"-....","--...","---..","----.",".-.-.-","--..--","..--.."};
int userSelection;
string resultString;
cout << "TEXT TO MORSE CODE or MORSE CODE TO TEXT program" << endl << endl;
cout << "Please select an option by typing the integer shown: " << endl << endl;
cout << "Type(Selects option) 1 to decode Morse code to English text" << endl;
cout << "Type(Selects option) 2 to encode English text to Morse code" << endl;
cout << "Type(Select option) any other integer that is NOT 1 or 2 to QUIT" << endl << endl;
cin >> userSelection;
while(userSelection == 1 || userSelection == 2)
{
if(userSelection == 1)
{
string userInput;
cout << endl << "Enter English text to encode to Morse code,
with only a space between words: " << endl << endl;
cin.ignore();
getline(cin,userInput); //code works with both "This" and "This code"
cin.clear();
resultString = textToMorse(alphabet, morseAlphabet, userInput); //function modified
//to take one more
//parameter
cout << endl << "This is the Morse code decoded to English text: " << endl << endl;
cout << resultString << endl << endl << endl << endl;
}
}
return 0;
}
string textToMorse(const string alphabet, const string morseAlphabet[], string userInput)
{
//code, but program works.
string encodedEnglishText = "";
for(int i = 0; i < userInput.length(); i++)
{
userInput[i] = toupper(userInput[i]);
}
for(int i = 0; i < userInput.length(); i++)
{
encodedEnglishText += morseAlphabet[alphabet.find(userInput[i])];
encodedEnglishText += " "; // extra spacing added for output clarity
if(userInput[i] == ' ')
{
encodedEnglishText += " "; // extra spacing added for output clarity
}
}
return encodedEnglishText;
}
I didn't include all of the code, just the parts I felt were relevant to the question.
by works I mean:
getline successfully takes input. getline successfully assigns a string such as "this" and "this code" to the variable userInput when used in main function.
it only successfully assigns strings without spaces such as "this" when used in my user defined function. In that function, for some reason it does not work when I enter a string like "this code" or any string with a space inbetween.
note: program is not finished, as I plan to add other methods to do the reverse (as seen in code with
extra user options, but these are not yet implemented or defined, code still runs and compiles for problem I am facing.
The problem is that there is no morse code for a space.
Make a verification:
int n = alphabet.find(userInput[i]);
encodedEnglishText += (n == string::npos) ? " ": morseAlphabet[n];
Then it will work.
When you are looking for your input character in the alphabet string you won't find ' ' and std::string::find() return std::string::npos (normally -1 converted to the type std::string::size_type but the value isn't guaranteed). Using this value to index morseAlphabet won't do you much good: it is undefined behavior. This problem does not arise when you enter just one string as all characters are found in alphabet.
The proper way to deal with the situation is to look for the character and capture the result. Before using the result, you'd test the input, e.g.:
std::string::size_type pos(alphabet.find(userInput[i]));
if (pos == std::string::npos) {
// deal with the character not being part of the alphabet
}
else {
encodedEnglishText += morseAlphabet[pos];
}
Note that there are a few other things wrong with your program:
The selection of options should be inside the loop! The way it is implemented entering, e.g. 2 results in an infinite loop.
Using std::toupper() with a char can also result in undefined behavior! The problem is that std::toupper() expects a non-negative value of the value EOF but char may be signed. To avoid this problem you should use any of the functions from <cctype> or <ctype.h> with unsigned char:
userInput[i] = toupper[static_cast<unsigned char>(userInput[i]));
If the user doesn't enter an integer but, e.g., foo reading userSelection will fail and stream will get into failure state where it won't do anything until std::cin.clear() is entered. The best approach to deal with this situation is to test the result of reading the value before doing anything. If the input failed you can recover from the situation by clearing the status and skipping the offending character, e.g.:
if (std::cin >> userSelection) {
// use the selection
}
else {
std::cout << "ignoring invalid input\n";
std::cin.clear();
std::cin.ignore();
}
Note that your use of std::cin.clear() should be needed. Also, you should verify that the input you read with std::getline() is successful: in general, all user inputs should be tested for success.
If you enter a space character after the integer when reading userSelection, your call to std::cin.ignore() will ignore this space not the newline! To avoid this problem you could either read all charactors up to the first newline or skip all whitespace prior to the non-whitespace character:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // all till newline
std::cin >> std::ws; // skip all whitespace to first non-whitespace character
Do not use std::endl! It does not only create a newline but it also flushes the stream. This can easily create a performance problem.
You should probably pass std::string arguments by reference rather than by value. Passing the argument alphabet by value creates a copy with is inefficient (the morseAlphabet argument is passed by pointer although it looks like an array).
Some string literals seem to be split across multiple lines. Doing so is illegal (I guess, however, that this problem was introduced when pasting the code to the question above at some point).

C++ Issue with cin and CTRL + Z

I'm reading c++ primer 5th and I have a little problem with an exercise:
Read a sequence of words from cin and store the values a vector. After
you’ve read all the words, process the vector and change each word to
uppercase. Print the transformed elements, eight words to a line.
My code is this:
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main(){
vector<string> words;
string wordBuffer;
vector<string> output(1);
while (cin >> wordBuffer){
words.push_back(wordBuffer);
}
for (string &word : words){
for (char &letter : word){
letter = toupper(letter);
}
}
unsigned currentLine = 0;
for (decltype(words.size())index = 0; index < words.size(); ++index){
output[currentLine] += words[index] + " ";
if ((index+1) % 8 == 0){
++currentLine;
output.push_back("");
}
}
for (string s : output){
s[s.size() - 1] = 0; //removing the whitespace
cout << s << endl;
}
system("pause");
return 0;
}
Now, everything works well, but i have an issue with the input of the words by console.
If I write
I am writing a random words ^Z
and press Enter nothing happens. I have to rewrite the ^Z after I have pressed the Enter, like here:
I am writing a random words
^Z
Can you expain me why? Thanks!
PS: I'm saying that because in my previous programs writing ^Z in the same line worked fine. Like in this code:
#include <iostream>;
int main(){
int currval = 0,val = 0;
int count = 1;
while (std::cin >> val){
if (currval == val){
++count;
}
else {
std::cout << "The number " << currval << " appears " << count << " times" << std::endl;
currval = val;
count = 1;
}
}
std::cout << "The number " << currval << " appears " << count << " times" << std::endl;
system("pause");
return 0;
}
I can't figure out why :(
The ^Z has to be first in order for Windows to treat it as Ctrl+Z, otherwise it is just treated as meaningless characters.
If you would like it to work like you wrote i'd suggest:
String wordBuffer("")
while (strcmp(wordBuffer[strlen(wordBuffer)-3], "^Z") != 0){
words.push_back(wordBuffer);
cin >> wordBuffer
}
EDIT: in your second example it works because when you read integers c++ knows to divide the given string of numbers in the space (or ENTER if the numbers are entered separately in every line) to read every number separately so if you'll enter:
123 2323 4545 43 ^Z
It will read 123, then 2323, ... and then ^Z and so it will be as though it got it in a separate line but when you read string, it cant do that because a string contain every symbol and so it separate the input in the ENTER pressed and that why the second one works
As far as I know Ctrl+Z is placed in the keyboard buffer before any other entered symbols. Thus any entered characters before Ctrl+Z will be discarded. You need to do the following
I am writing a random words ENTER
^Z ENTER

Using Arrays for test results

Okay, so I know that you guys aren't my own personal programmers but I was wondering if you could help me out a bit here. I work as a teachers assistant while I'm going to school. I know a bit of C++ and was trying to make a basic program to check answers with.
The first part of the program works fine to test the answers against the key, however the second part is what I'm having issues with. I'm trying to find how many students answered what question so I don't have to count them by hand, but I cannot seem to get this down.
What I really need is to be able to print them out like so:
question A B C D E
1 1 12 3 5 7
and so on.
I know I'm probably going to need a nested for loop, but I've been banging my head on this all night. Any help would be appreciated.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void main(){
int numstud=0, numcorrect, i;
string key, id, responses;
ifstream keyfin, studfin;
keyfin.open("answers.dat");
studfin.open("tests.dat");
keyfin >> key;
studfin >> id >> responses;
cout << setw(5) << "Student-Id's" << setw(20) << "# Correct" << endl << endl;
while(!studfin.eof())
{
numstud++;
numcorrect=0;
for(i=0; i<20; i++){
if(responses[i] == key[i])
{
numcorrect++;
}
}
cout << id << setw(20) <<numcorrect << endl;
studfin >> id >> responses;
}
studfin >> id >> responses;
int col[20][5]={0}, j=0;
char ch;
studfin >> id >> responses;
cout << "Question" << setw(10) << "A" << setw(5) << "B" << setw(5) << "C" << setw (5) << "D" << setw(5) << "E";
while (!studfin.eof())
{
for(i=0; i<responses.length(); i++)
{
col[i++][responses[i-'a'] ++];
}
}
}
You have the general idea as far as implementing an histogram of the responses. However there are a few things wrong with the line col[i++][responses[i-'a'] ++].
First assuming responses are lower case, you probably intended responses[i]-'a' rather than responses[i-'a'], to convert the letter grade to a 0,1,2,3,4 index.
Then, it's the content of the table you want to increment, not row and column indices. That is col[i][responses[i]-'a']++.
As a side note, you don't need a second while (!studfin.eof()) loop to update the histogram. You can keep updating it as you are checking answers against the key (and you should not use a second loop unless you reset the input stream that has reached end-of-file by the end of the first loop).

How I can manage to keep white space in my String from user input

I'm coding a little console application in C++ and in it I take a string from the user:
cin >> themainstring;
int si = 0;
while (themainstring[si] != '+' || themainstring[si] != '-' ||
themainstring[si] != '*') {
if (themainstring[si] == '+' || themainstring[si] == '-' ||
themainstring[si] == '*') {
lmnopt = themainstring[si];
break; // while
}
si++;
}
int strlenthestring = themainstring.size();
lmnop1 = themainstring.substr(0, si);
lmnop2 = themainstring.substr(si + 1, strlenthestring);
So for example, when I give this input:
ilove+programming
I want to try and cut the string when I see +, - and *. which works fine.
However I want my code to do the same when I input:
ilove + programming (white spaces after and before arithmetical operator)
I have messed around with the WS but I couldn't understand the logic.
Actually the main problem of mine is about C++'s space logic. Why it thinks the space will explode the string input?
I'm not sure I've understood this question completely correctly, however I thought I'd pitch in with some help.
First off, when it comes to looking through strings, C++ has a great set of functions as standard that does that. Point your browser to: Basic String Library.
This contains all the functions you can carry out on a string in C++.
Secondly, something else you need to be aware of, is that you are using std::cin to read user input from the keyboard. By default, cin ignores white spaces, so for example, the following code:
string inputString;
cin >> intputString;
cout << "Input String is: " << inputString << endl;
and let's assume you entered Hello World in as your user input, the program would only output "Hello"
So what you need to do is to use getline. Which allows for whitespaces in your user inputs. And you use it as follows:
std::getline(cin, inputString);
So to give an example where it all gels together:
#include <iostream>
#include <sstream> // for istringstream
#include <string>
using namespace std;
int main(int argc, char * argv[])
{
string inputString;
cout << "Please Enter String: ";
getline(cin, inputString);
cout << "\n" << endl;
cout << "InputString is: " << inputString << endl;
// So you can do something like this
string searchTerm("+");
// Find first of is an operating you can carry out
// on a string so you don't have to use loops.
cout << "Position: " << inputString.find_first_of(searchTerm) << endl;
int pos = inputString.find_first_of(searchTerm);
string part1 = inputString.substr(0, pos);
string part2 = inputString.substr(pos + 1, inputString.length());
cout << "Position of + is " << pos << endl;
cout << "part 1 is: " << part1 << endl;
cout << "part 2 is: " << part2 << endl;
}
Now I know I've only done this with the + sign, but it should serve as a starting point to getting to where you want to be.
Hope all this helps.

Reading a particular word in .txt file

I have a txt file which contains the name and roll number of students. I want to read and display a particular roll number from his file. It shows only the first roll number, but I want to read the roll number of the 2nd person.
That is, if I want to read the roll number of "ss", it shows the roll number of the first person
The program is
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>
void student_read()
{
clrscr();
char name[30], n[30], temp[30];
int i, roll_no, code, count=0;
ifstream fin("tt.txt",ios::in|ios::beg);
if(!fin)
{
cout << "cannot open for read ";
return;
}
cout << "Enter the name of student" << "\n";
cin >> n;
while(fin >> name >> roll_no)
{
cout << roll_no << endl;
}
if(string[name] == string[n])
{
cout << "roll no" << "\n" << roll_no;
}
else
cout << "Not found";
}
void main()
{
clrscr();
cout << "Students details is" << "\n";
student_read();
getch();
}
The txt file contains this data:
sourav
123
ss
33
Does you have end of each line in your text file? Does you have sourav 123 ss 33 or sourav 123\nss 33?And this if(n[30]==name[30]) compare only 1 character in string.
You're doing the output of what is in the file already before you even input the name to search for.
Reorder your statements, like this:
cout<<"Enter the name of student"<<"\n";
cin>>n;
while(fin>>name>>roll_no)
{
//...
Also, if you only want to output one name and roll_no, in your loop, you have to check some kind of condition whether to print or not. At the moment, your code should actually print the roll_no of all rows in the file, and possibly sometimes the last one twice.
So the condition you have after the input belongs into the loop.
Additionally, however, you're only comparing the 31st character of the char array (which is actually already out of the bounds of your array variables! Their indices go from 0..29, i.e. even if you allocated a 30 characters array, the ). That means, your condition will be true if the next to last character matches. This place will most likely not be initialized yet, so you compare basically gargabe values and will get unexpected/random results.
If you want to, as the description suggests, want to compare the whole char array, that works differently by the way (not with the == operator, that would only compare pointer addresses), you'd need to use the strcmp function. But even better would be to use std::string instead of char *.
void student_read()
{
clrscr();
std::string name, n, temp;
int i, roll_no, code, count = 0;
std::ifstream fin("tt.txt", ios::in | ios::beg);
if (!fin)
{
std::cout << "cannot open for read ";
return;
}
std::cout << "Enter the name of student" << "\n";
std::cin >> n;
while (fin >> name >> roll_no)
{
std::cout << roll_no << std::endl;
}
if (name == n)
{
std::cout << "roll no" << "\n" << roll_no;
}
else
std::cout << "Not found";
}
int main()
{
clrscr();
std::cout << "Students details is\n";
student_read();
getch();
}