I have an array that holds strings. I was wondering if there's any way to add X amount of chars to the string in the array.
For example if a user inputs the number 10 and then the letter A, I want stringarray[x] to have the value of AAAAAAAAAA.
At the moment I am using a for-loop but I was wondering if there is an easier and more efficient way of doing this. One that doesn't require a loop.
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
#include <fstream>
using namespace std;
int main(){
char letter;
int number;
string stringarray[5] = {" "};
cin >> letter; // letter to add
cin >> number; // number of times
cout << stringarray[1]; // here I want the result to be letter x number
return 0;
}
I can only use these libraries.
I don't think it's necessary to post my for-loop since it already works. I am only wondering if there's any way to do it without the loop.
A C++ way of doing this is to use std::string s(10, 'A'); and get const char *stringarray = s.c_str() from it if you need a const char *.
Related
So I make an array of string pointers and put a string in at position 0 of the array. If I don't know the length of the string in word[0] how do I find it? How do I then manage that string, because I want to remove the "_." and "." part of the string so I will be left with "apple Tree".How do I resize that string? (functions like strcpy,strlen, or string.end() didn't work, I get errors like "can't convert string to char*" etc)
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int counter=0;
string* word = new string[0];
word[0] = "apple_.Tree.";
return 0;
}
Edit:what i want to do is make a dynamic array of strings(not using vector) and then edit the strings inside
string is a class, so you can use its member functions to manage it. See the documentation.
To remove characters, use std::erase (see this answer).
#include <iostream>
#include <string>
#include <algorithm>
int main() {
// Create array of 10 strings
std::string array[10];
array[0] = "apple_.Tree.";
std::cout << array[0].size() << "\n";
array[0].erase(std::remove(array[0].begin(), array[0].end(), '.'), array[0].end());
array[0].erase(std::remove(array[0].begin(), array[0].end(), '_'), array[0].end());
std::cout << array[0];
return 0;
}
I have an input file which I'm reading in with the basic myFile >> variable since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num> and to make >> work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
First to get the middle character out you can just do char myChar = inputString.at(1);. Then you can do int myInt = (int)myChar;
Even if you remove the <> characters, your still importing the file content into a string using >> so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
You can also resort to sscanf.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}
How do I limit the user input on the number of variable I want ?
ie
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
int main{
char variable1, variable2, variable3;
cin >> variable1 >> variable2 >> variable3;
}
If the user input 2 3 4 5, i don't want the 4th value to go into the next input i have. Any idea?
I have tried using setw(10) to limit then but it seems doesn't work as well.
Try using different cins (separate ones) for example:
cin>>variable1;
cin>>variable2;
cin>>variable3;
This would prevent saving multiple variables and generate an error if a user types "4 5"
It's not quite simple, but it's wholly doable.
You need to ensure that your program stops reading the input stream after it gets the first 3 inputs, separated by whitespaces. If you work with "getline(t, param, delim)" instead of just "cin", you'll have more options available to you. In a nutshell, getline is a function in the library that lets you take (from_somewhere, to_somewhere, stop_reading_here). For you, you'll be reading in from the "cin" stream, so it should look something like this:
getline(cin, random_string_variable_name, ' ');
The third parameter, the delimiter, is a space between two apostrophes. It's telling the function that whatever it's read in through 'cin' ends when it gets to the first space. If you try this code:
#include <string>
#include <iostream>
using namespace std;
int main() {
string variable[3];
for (int i = 0; i < 3; i++)
getline(cin, variable[i], ' ');
for (int i = 0; i < 3; i++)
cout << variable[i] << " ";
}
you'll find that "1 2 3 4 5" would return "1 2 3 ". Tell me if you need explanation on the square brackets or "for" loops, though you really should google that first if you don't.
As you are writing "If the user input 2 3 4 5, i don't want the 4th value to go into the next input i have.", I think your main interest is not limiting the input, but avoiding negative effects from additional input. This can be achieved by reading the user input into one string and extraction the integers from the string:
#include <string>
#include <iostream>
using namespace std;
int main() {
string line;
getline(cin, line);
// parse line to extract the single numbers
}
I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:
input: write this backwards
sdrawkcab siht etirwˇ
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}
The buffer reverse needs to be message.length() + 1 in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.
I have an integer 1 and i want to display it as a character '1' in C++. So far I have only managed to convert it from say integer 65 to character 'A'.
How do you stop this ?
int theDigit = 1;
char ch = theDigit+'0';
This works because it's guaranteed1 that the sequence of characters '0'...'9' is contiguous, so if you add your number to '0' you get the corresponding character. Obviously this works only for single digits (if theDigit is e.g. 20 you'll get an unrelated character), if you need to convert to a string a whole number you'll need snprintf (in C) or string streams (in C++).
C++11, [lex.charset] ¶3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
By the way, I suppose that they didn't mandate contiguity also in the alphabetical characters just because of EBCDIC.
Use the stringstream.
int blah = 356;
stringstream ss;
string text;
ss << blah;
ss >> text;
Now text contains "356"(without quotes). Make sure to include the header files and use the namespace if you are going to copy my code:
#include <sstream> //For stringstream
#include <string>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
int i = 3;
char buffer [25];
itoa (i, buffer, 10);
printf ("Integer: %s\n",buffer);
Integer: 3
You did just ask about printing an integer, so the really simple c++ answer is:
#include <iostream>
int main()
{
int value = 1;
std::cout << value << endl;
return 0;
}