Updating a string through iteration in C++ - c++

OK, so I'm trying to make a string thing, so that the string is updated. Sort of like you have a string "hello" and I want it to update itself somewhat like "h" "he" "hel" "hell" "hello"
So, I have:
#include <iostream>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
system("title game");
system("color 0a");
string sentence = "super string ";
for(int i=1; i<sentence.size(); i++){
cout << sentence.substr(0, i) <<endl;
}
return 0;
}
The code returns out like:
"s
"su"
"sup"
"supe"
"super"
Obviously on different lines, but when I remove the end line, the sentence builder just goes berserk. It displays something like "spupsppuepr sttrrtrsubstringsubstring"
Is there anyway I can update the string on THE SAME LINE? (and not have it completely destroyed)

You could print a carriage return character '\r' at each iteration, returning the cursor to the beginning of the line:
for(int i=1; i<sentence.size(); i++){
cout << '\r' << sentence.substr(0, i);
}
Or just output each character in sequence:
for(int i=0; i<sentence.size(); i++){
cout << sentence[i];
}
You probably also want to insert a short delay for each loop iteration to achieve a typewriter effect.

Running your code produces this:
./a.out
ssusupsupesupersuper super ssuper stsuper strsuper strisuper strinsuper string
This is exactly what you tell it to do. It's the same as with the endl but without the newlines. If you don't want it to repeat all the letters, you need to iterate through the string itself, not through the substrings.
using namespace std;
int main()
{
system("title game");
system("color 0a");
string sentence = "super string ";
for(int i=0; i<sentence.size(); i++){
cout << sentence[i];
}
return 0;
}

My advice: use While loop.
#include <stdio.h>
#include <iostream>
int main() {
system("title game");
system("color 0a");
char* sentence = "super string";
while( *sentence ) std::cout << *sentence++;
return 0;
}

Related

How do I flip the first number in the string with the last number and then second and second last and so on?

Here's what I tried and it's not logical. First_num++ is just copying 2 numbers instead of the second number and so is the last_num++
How do I continue copying like that and cout them
I know I can just cout the thing in reverse because the output is the same.I can do that by reversing the count but the question wants me to exchange the characters one by one. Please help, thanks.
#include <iostream>
#include <cctype>
using namespace std;
void reverse_word(char character[]);
int main()
{
char characters[50];
reverse_word(characters);
return 0;
}
void reverse_word(char character[])
{
char temp1[2] = "\0";
char temp2[2] = "\0";
char first_num = 1;
char last_num = 1;
cout << "Enter a word to reverse first word last word second first second last and so on: ";
cin >> character;
for (int i=0;i<strlen(character)/2;i++)
{
strncpy(temp1, character, first_num);
first_num++;
strcpy(temp2 , &character[strlen(character)-last_num]);
last_num++;
}
for (int i = 0; i < strlen(character) / 2; i++)
{
cout << temp2;
cout << temp1;
}
}
You can use the build-in function of c++ reverse(begin, end) where the begin and end iterator are as parameter like below:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "String example";
reverse(str.begin(), str.end()); // outputs --> elpmaxe gnirtS
cout<<"\n"<<str;
return 0;
}
This is a short and fast solution , but if you want to get a more depth view you can apply some nice alogrithm .
You should cout the temp variables in the same for loop, not in a different one.

Writing a C++ program to print the letters of a string in a chaotic order

What I'm trying to do is this:
User enters a string (For example: "Hello")
The program returns the same string, but in a random order(It can be "elHlo" or any other order possible)
So far I've written this code, but the problem is that sometimes the randomly generated numbers are the same, so it might print the same indexes(letters) twice or more times:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
for(unsigned int j=0; j<text.length(); j++){
int randomLetter = rand()%text.length();
cout << text.at(randomLetter);
}
return 0;
}
Can anyone help me fix it?
You can use std::shuffle (since C++11):
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
std::mt19937 g(time(0));
std::shuffle(text.begin(), text.end(), g);
cout << text;
return 0;
}
Or std::random_shuffle (if you are using old specification):
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
std::random_shuffle(text.begin(), text.end());
cout << text;
return 0;
}
Instead of calling rand() one time, which can generate an index you have called before, you can keep generating a new index while keeping tracking of all generated indices in a hashtable.
std::unordered_map<int, bool> done;
for (unsigned int j = 0; j < text.length(); j++) {
int randomLetter = rand() % text.length();
while (done[randomLetter] == true) // while it's been marked as finished, generate a new index.
randomLetter = rand() % text.length();
cout << text.at(randomLetter);
done[randomLetter] = true; // mark it as finished.
}
Alternatively, you can use std::random_shuffle instead, which should save you the hassle.
std::random_shuffle (text.begin(), text.end());
std::cout << text << '\n';

Is there a better way I could be receiving this input? C++

Currently just trying to edit some basic input to get rid of a singular '.' at the beginning of a line.
However, this only functions when I force EOF. My submission review for this assignment on the uni site seems to be getting stuck in the while loop and not outputting the result. The amount of input can be up to 1000 lines and I can't seem to think of how I could best receive this input without it getting stuck like this. main.cpp below:
Example input and output would be:
Input:
..hello
.hello
hello
Output:
.hello
hello
hello
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
string inputLine;
vector<string> vect;
string s;
string temp;
while (getline(cin, s)) {
vect.push_back(s);
}
for (int i = 0; i < (int)vect.size(); i++) {
temp = vect[i];
if (temp[0] == '.') {
for (int k = 0; k < (int)temp.length(); k++) {
temp[k] = temp[k + 1];
}
}
vect[i] = temp;
}
for (int j = 0; j < (int)vect.size(); j++) {
cout << vect[j] << endl;
}
return 0;
}
The tester of your program is probably opening a pipe and waiting for your program to output the first line before sending the second. A case of dead-lock.
If you want to ignore the . character you can use std::basic_istream::peek to check if the line starts with this character and then simply std::basic_istream::ignore it. You may also want to flush your output for each line, using std::endl will do.
#include <string>
#include <iostream>
int main() {
std::string line;
while(std::cin) {
if(std::cin.peek() == '.')
std::cin.ignore();
if(std::getline(std::cin, line))
std::cout << line << std::endl;
}
}

How to properly use getline in c++

I am trying to for loop a string and put it inside a map in C++ but for some reason, it keeps excluding myMap[0] and I can't output the first letter of my strings. Please help.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
int inputNumbers;
map<int,string>myMap;
cout<<"Enter how many words"<<endl;
cin>>inputNumbers;
//insert the words to the map
for(int i = 0; i < inputNumbers; i++) {
string inputNames ="";
cout<<"Enter the word #"<<i+1<<" out of "<<inputNumbers<<endl;
getline(cin, inputNames);
myMap[i] = inputNames;
cin.clear();
cin.ignore();
}
//output map
for(map<int,string>::iterator it = myMap.begin(); it != myMap.end(); it++)
cout << it->first << ":" << it->second << endl;
it->first << ":" << it->second << endl;
return 0;
}
And this is the output
Enter how many words
4
Enter the word #1 out of 4
Kobe
Enter the word #2 out of 4
is
Enter the word #3 out of 4
the greatest
Enter the word #4 out of 4
ever!!!
0:
1:obe
2:s
3:he greatest
Program ended with exit code: 0
Would also appreciate an extra tip that scans a user input string and output if it is a string word (no whitespace), real word (only letters), goodword (letters and numbers), capword (begins with a capital letter), acronym (all caps string).
I found an answer!!!!
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
string inputNames;
int main()
{
string line;
vector<string> myVector;
ifstream myTextFile("myText.txt");
//stores the lines in file to myVector and pushes it back
while (getline(myTextFile, line)) {
//cout<<line<<endl;
myVector.push_back(line);
}
//outputs what's inside the vector
for(int i=0; i<myVector.size(); i++) {
cout << i << ":" << myVector[i] << endl;
}
return 0;
}

My for loop keeps looping and causes the program to crash

I'm trying to make a program that will receive a string and output an uppercase version of that. My code works, however once it loops through the string and changes it, it immediately crashes and I'm not completely sure why. Here are my two pieces of code.
/*This program is to intended to receive a string and return a version of it in all upper case*/
#include <iostream>
#include <string>
#include <locale>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++;)
std::cout << std::toupper(str[i]); //A loop which goes through each digit of the string
break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
/*This program calls a function to make a string in upper case*/
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
#include "toUpper1.h" //Calls the header file which contains the loop
using namespace std;
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
cout<<toUpper(input); //The command that causes the user input string to be transformed into upper case
return 0;
}
You can make string to uppercase using code bellow
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Or use like this
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
You are breaking the function without returning anything. Use {} to close for loops if you want to use break
prog.cpp:16:5: error: break statement not within loop or switch
break;
Also your for loop has an extra ; at the end.
std::cout and std::toupper are useless as you are already including namespace std;
and why are you using break;? there is no need of it.
just write
for (int i=0; i<str.length(); i++)
cout << toupper(str[i]);
Remove break;
You are not transforming the string, you are outputting its transformation in the function.
instead of
std::cout << std::toupper(str[i]);
use
str[i]=std::toupper(str[i]);
And move all printing out of the function. Changing the string doesn't include printing!
Notice the #bbdude95 answer, too.
edit
Instead of
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input;
use
char input[256];
cout << "Please type in a word:\n>";
cin.getline( input, 256, '\n' );
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++)
str[i] = std::toupper(str[i]); //A loop which goes through each digit of the string
//break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
//The command that causes the user input string to be transformed into uppe case
cout << toUpper(input);
cout << std::endl << "The original string is" << input << std::endl;
return 0;
}
EDIT: Note that keeping the function signature as above (string toUpper ( string str), as were required), we are making some extra string copies, and, most important: we are NOT modifying the original string (excute the code and see the result of last cout.