Regarding accessing letters of strings in C++ - c++

#include <iostream>
#include <string>
using namespace std;
int main() {
int n;cin>>n;//entering number of string to be inputed
string a[n];//declaring an array of type string
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cout<<a[i]<<endl;
}
//for manipulating letters of strings
cout<<a[0][1];
return 0;
}
To access the elements of a string, we should output the result as a multidimensional array. This seems a bit counter intuitive. Could someone explain is this the right way.
Input
2
asfdsf
asfdsafd
Output
asfdsf
asfdsafd
s

A string is an array of characters. So an array of strings is an array of arrays of characters. To access the jth character in the ith string, you use a[i][j].

You cannot declare:
string a[n]; //declaring an array of type string
Why?
ISO C++ forbids variable length array ‘a’
Instead, you should use a vector of string and .push_back() each new string you add, e.g.
#include <iostream>
#include <string>
#include <vector>
int main (void) {
int n = 0;
std::cout << "enter the number of strings: ";
std::cin >> n;
if (n < 1) {
std::cerr << "error: invalid number of strings.\n";
return 1;
}
std::vector <std::string> a; // vector of strings
for (int i = 0; i < n; i++) { /* read each string */
std::string tmp;
std::cin >> tmp; /* into a temp string */
if (!std::cin.eof() && !std::cin.fail()) /* validate read */
a.push_back(tmp); /* add string to vector */
/* output string and first character using indexes */
std::cout << "string[" << i << "]: " << a[i] << " (a[" << i
<< "][0]: " << a[i][0] << ")\n";
}
}
Example Use/Output
$ ./bin/stringindex
enter the number of strings: 4
My
string[0]: My (a[0][0]: M)
Dog
string[1]: Dog (a[1][0]: D)
Has
string[2]: Has (a[2][0]: H)
Fleas!
string[3]: Fleas! (a[3][0]: F)
Look things over and let me know if you have any questions.

Related

How to read from keyboard a variable number of integers in C++?

I need to read a variable number of integers from keyboard so that I can use each of them.
First I thought I could use something like
int myinteger;
for (int i=0; i<MAX_NUMBER_OF_INTEGERS; i++){
cin >> myinteger;
//What I want to do with that Integer
}
But then I realized that if MAX_NUMBERS_OF_INTEGERS = 10 I have to write 10 integers. But what I want is that I can pass "1 2 3" "1 2 3 4" (for example) and not necessary write 10 integers.
The question seems to have changed a little bit since it was asked and a good answer was given. This just serves to answer the new questions.
#include <iostream>
#include <sstream>
#include <vector>
const int MAX_NUMBERS_OF_INTEGERS = 10;
int main() {
std::string line;
std::cout << "Enter at most " << MAX_NUMBERS_OF_INTEGERS << " ints, separated by spaces: ";
std::getline(std::cin, line);
// create a string stream of the line you entered
std::stringstream ss(line);
// create a container for storing the ints
std::vector<int> myInts;
// a temporary to extract ints from the string stream
int myInteger;
// extract at most MAX_NUMBERS_OF_INTEGERS ints from the string stream
// and store them in the container
while(myInts.size()<MAX_NUMBERS_OF_INTEGERS && ss>>myInteger) myInts.push_back(myInteger);
std::cout << "Extracted " << myInts.size() << " integer(s)\n";
// loop through the container and print all extracted ints.
for(int i : myInts) {
std::cout << i << "\n";
}
// ... or access a certain int by index
if(myInts.size() > 2)
std::cout << "The third int was: " << myInts[2] << "\n";
}
std::vector<int> read_ints;
int _temp;
for(;;)
{
cin >>_temp;
if(!cin.good()) {
break;
}
else {
read_ints.push_back(_temp);
}
}
I haven't tested this solution but it should read an arbitrary number of ints from cin until you enter something else than an integer. You could also skip the saving in the vector part if you don't need to save the results. This is just releveant if you want to save an arbitray number of integers.
EDIT: After clarification your solution could look like this:
int MAX_CHARS = 10;
int my_int;
cin >> setw(MAX_CHARS) >> my_int;
setw limits the number of input characters but you have to include iomanip header
If you want to access every digit, convert int to vector of ints with this function:
vector <int> integerToArray(int x)
{
vector <int> resultArray;
while (true)
{
resultArray.insert(resultArray.begin(), x%10);
x /= 10;
if(x == 0)
return resultArray;
}
}
then you can access each digit with the index e.g. first digit
vectory<int> resultArray = integerToArray(my_int);
int digit = resultArray[0];
Source
One way to read all numbers from a single line limiting them to a maximum number of integers is using std::getline() to get the line into a string then use istringstream in a loop.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
std::string line;
std::getline (std::cin,line);
std::istringstream iss(line);
int myInt;
for(int i=0;(iss >> myInt) && (i < MAX_NUMBER_OF_INTEGERS);++i ) {
std::cout << myInt << ' ';
}
return 0;
}
Note: I did not define MAX_NUMBER_OF_INTEGERS in the code. I could have defined it with const int MAX_NUMBERS_OF_INTEGERS = 10; before usage or possibly that could be a preprocessor define or even a command line parameter. I leave this up to the user.

How to reverse the string

I'm a beginner at coding and was given a project by a friend to reverse the order of a string inputted by the user, however when I run this code the program just repeatedly prints the string inputted many times over and I'm not sure whats wrong.
For instance, I input "hi", it just prints "hi" many times. I have tried using cin, getline and scanf (as recommended by a friend), but to no avail...
#include <iostream>
using namespace std;
int main()
{
char arr[5];
getline(cin, arr);
for(int x=4; x>=0; x--){
cout << arr << endl;
}
return 0;
}
Since the question is tagged C++, you should use C++ constructs such as std::string and std::reverse. This will result in more readable and understandable code.
#include <string>
#include <iostream>
#include <algorithm>
int main()
{
std::string input;
std::getline(std::cin, input);
std::reverse(input.begin(), input.end());
std::cout << input << std::endl;
return 0;
}
This line is wrong:
cout << arr << endl;
You have to use the index operator [] like this:
cout << arr[x];
Note that there is no endl, as that would print every character in a new line.
Using arr[x] gives you the element of the array (or character of the string if you will) at index x. Please note that element indexes in C++ start at 0. So the first element is arr[0], second arr[1], and so on.
Also, why use a C-style char array of only size 5? You can use the C++ std::string just as effectively and it will work for larger strings:
string x;
getline(cin, x);
for (int i = x.size() - 1; i >= 0; i--)
{
cout << x[i];
}
cout << endl;
Hope this helps.
When you write, cout << arr << endl; you are printing the entire string in each iteration of the loop. Instead, you wish to print the character at the index x, so you should write it as cout << arr[x]; If you use endl inside the loop, you will get a new line after each character.
Moreover, in C++, there is an easier way to deal with strings, using the string library. Then, you need not specify the number of characters in your string beforehand, and helps if the user needs to enter more than 4 characters.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string arr;
getline(cin, arr);
for(int x=arr.size()-1; x>=0; x--){
cout << arr[x];
}
cout << endl;
return 0;
}
What's happening is you're sending the entire contents of arr to cout 5 times. What you want instead is to print each character in reverse; to do this, you need to send only one character of arr at a time inside your for loop:
cout << arr[x] // This sends the character at index x to cout
cout << arr // This sends the entire array to cout
Also, you should have cout << endl after the for loop; otherwise, you'll print a newline character after each letter.
Alternate solution using iterators:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
int main()
{
std::string input;
getline(std::cin, input);
for (std::string::reverse_iterator rit=input.rbegin(); rit!=input.rend(); ++rit)
std::cout << *rit;
return 0;
}

C++ program using vectors

I'm having difficulties finding the problem here , the program must read a number N and then read 2 vectors with N lenght, multiply each number of the first vector with the relevant number of the second one and substract each of the previous multiplies (example A[0]*B[0] - A[1]*B[1] .... A[N-1]*B[N-1] ) Any replies will be greatly appreciated.
Input values : 3/
1 2 -3
/4 -5 -6
Output : -4
Here's the code:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
using namespace std;
/* Splits string using whitespace as delimeter */
void split_input(vector<double> &vector_values, const string &input)
{
char delim = ' ';
stringstream mySstream(input);
string temp;
while(getline(mySstream, temp, delim))
{
vector_values.push_back(atof(temp.c_str()));
}
}
double multiply(vector<double> &first_vector, vector<double> &second_vector)
{
double result = 0;
for(int i = 0; i < first_vector.size(); i++)
{
if (i == 0)
{
result = first_vector[i]*second_vector[i];
}
else
{
result -= first_vector[i]*second_vector[i];
}
cout << result << endl;
}
return result;
}
int main()
{
vector<double> first_vector;
vector<double> second_vector;
int num;
string input_values;
cout << "Please enter a number: " << endl;
cin >> num ;
/* Ignores the endline char from the previous cin */
cin.ignore();
/* Read first string, split it and store the values in a vector */
getline(cin, input_values);
split_input(first_vector, input_values);
cin.ignore();
/* Read second string, split it and store the values in a vector */
getline(cin, input_values);
split_input(second_vector, input_values);
/* Multiply vectors */
cout << multiply(first_vector, second_vector) << endl;
return 0;
}
Remove cin.ignore() after split_input(first_vector, input_values);. With cin.ignore() the first element of the second vector is alway 0. Your main() should look like this:
int main()
{
vector<double> first_vector;
vector<double> second_vector;
int num;
string input_values;
cout << "Please enter a number: " << endl;
cin >> num ;
/* Ignores the endline char from the previous cin */
cin.ignore();
/* Read first string, split it and store the values in a vector */
getline(cin, input_values);
split_input(first_vector, input_values);
// following line causes the first element of the second vector to become 0
// cin.ignore();
/* Read second string, split it and store the values in a vector */
getline(cin, input_values);
split_input(second_vector, input_values);
/* Multiply vectors */
cout << multiply(first_vector, second_vector) << endl;
return 0;
}

How to user input the array elements in c++ in one line

I am new to c++ , Basically I belong to PHP . So I am trying to write a program just for practice, to sort an array . I have successfully created the program with static array value that is
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject;
int main () {
int myints[] = {55,82,12,450,69,80,93,33};
std::vector<int> myvector (myints, myints+8);
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
its output is ok . But I want that the elements should input from user with space separated or , separated . So i have tried this
int main () {
char values;
std::cout << "Enter , seperated values :";
std::cin >> values;
int myints[] = {values};
/* other function same */
}
it is not throwing an error while compiling. But op is not as required . It is
Enter , seperated values :20,56,67,45
myvector contains: 0 0 0 0 50
3276800 4196784 4196784
------------------ (program exited with code: 0) Press return to continue
You can use this simple example:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
stringstream ss;
string str;
getline(cin, str);
replace( str.begin(), str.end(), ',', ' ');
ss << str;
int x = 0;
while (ss >> x)
{
cout << x << endl;
}
}
Live demo
or, if you want to have it more generic and nicely enclosed within a function returning std::vector:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T>
vector<T> getSeparatedValuesFromUser(char separator = ',')
{
stringstream ss;
string str;
getline(cin, str);
replace(str.begin(), str.end(), separator, ' ');
ss << str;
T value{0};
vector<T> values;
while (ss >> value)
{
values.push_back(value);
}
return values;
}
int main()
{
cout << "Enter , seperated values: ";
auto values = getSeparatedValuesFromUser<int>();
//display values
cout << "Read values: " << endl;
for (auto v : values)
{
cout << v << endl;
}
}
Live demo
Read in all the values into one string, then use a tokenizer to separate out the individual values.
How do I tokenize a string in C++?
The above answers are very good for an arbitrary number of inputs, but if you allready know how many numbers will be put, you could do it like:
int[5] intList;
std::cin >> intList[0] >> intList[1] >> intList[2] >> intList[3] >> intList[4]
But please note that this method does not do any check if the numbers are put properly, so if there are for example letters or special characters in the input, you might get unexpected behavior.
Let's see what you wrote:
int main () {
char values;
std::cout << "Enter , seperated values :";
std::cin >> values; // read a single character
int myints[] = {values}; // create a static array of size 1 containing the single character converted to an int
/* other function same */
}
what you need is:
#include <sstream>
#include <string>
...
int main () {
std::cout << "Enter space seperated values :";
std::vector<int> myvector;
std::string line;
std::getline(std::cin, line); // read characters until end of line into the string
std::istringstream iss(line); // creates an input string stream to parse the line
while(iss >> value) // so long as values can be parsed
myvector.push_back(value); // append the parsed value to the vector
/* other function same */
}
If you want comma separated input you'll need to parse the comma as a single character in addition to the integer values.
What you are doing
int main () {
char values; //Declare space for one character
std::cout << "Enter , seperated values :"; //Ask user to enter a value
std::cin >> values; //Read into values (one value only)
int myints[] = {values}; // assign the first element to the ASCII code of whatever user typed.
/* other function same */
}
In the language char works as an 8-bit integer. Through function overloading, different behavior can be implemented. Read about static polymorphism for more details how it works.
What you need to do
std::vector<int> values;
char ch_in;
std::string temp;
while(cin.get(ch_in)) {
switch(ch_in) {
case ',':
case ' ': //Fall through
values.push_back(atoi(temp.c_str()); //include cstdlib for atoi
temp.clear();
break;
default:
temp+=ch_in;
}
}
You should put this in a separate function. With this skeleton, you can implement a more fancy syntax by adding more cases, but then you need something else than a std::vector<int> to put things into. You can (should?) also add error checking in the default case:
default:
if( (ch_in>='0' && ch_in<='9')
|| (temp.size()==0 && ch_in=='-') ) {
temp+=ch_in;
}
else {
cerr<<ch_in<<" is an illegal character here."
temp.clear();
}
#include <iostream>
#include <string>
#include <sstream>
#include <string.h>
using namespace std;
// THIS CODE IS TO GIVE ARRAY IN ONE LINE AND OF DESIRED LENGHT ALSO WITH NEGATIVE NUMBERS
// You can also do it by using ASCII but we Are using library name
// <sstream> to convert string charters to numbers
//O(n) time complexity
int main()
{
/*
// INPUT
// 7 array length
// 34-56-789 // without space b/w them */
int N;
cout << "Enter the size of the array " << endl;
cin >> N;
cout << "INPUT Without giving space b/w " << endl;
string strx;
cin >> strx;
int X[N]; // array to store num
int p = 0;
// NOTE USE HERE STRX.LENGHT() becouse we have to go through the whole string
for (int i = 0; i < strx.length(); i++)
{ // we have declare tempx to store a particular character
// one time
string tempx;
tempx = strx[i];
stringstream strtointx(tempx);
// this is the syntax to convert char to int using <sstream>
if (strx[i] == '-')
{
/*
The tricky point is when you give string as 1-23
here - and 2 are the separte characters so we are not
getting -2 as number but - and 2 so what we do is
we chek for '-' sign as the character next to it
will be treated as negative number
*/
tempx = strx[i + 1];
// by assigning strx[i+1] to tempx so that we can getting the which should be treated as negative number
stringstream strtointx(tempx);
// still it is a charter type now again using library
// convert it to int type
strtointx >> X[p];
X[p] = -X[p];
// now make that number to negative ones as we want it to be negative
i++;
// inside this if i++ will help you to skip the next charcter of string
// so you can get desired output
}
// now for all the positive ones to int type
else{ strtointx >> X[p]; }
p++; // finally increment p by 1 outside if and else block
}
// loop ends now get your desired output
cout<<"OUTPUT "<<endl;
for (int i = 0; i < N; i++)
{
cout << X[i] << " ";
}
cout<<endl;
cout<<"CODE BY MUKUL RANA NIT SGR Bch(2020)";
return 0;
}
// OUTPUT
/*
Enter the size of the array
7
INPUT Without giving space b/w
34-56-789
OUTPUT
3 4 -5 6 -7 8 9
CODE BY MUKUL RANA NIT SGR Bch(2020)
PS C:\Users\user\Desktop\study c++>
*/
// CAUTION :
/*
1) do not give input with spaces
**** if you do then first you have to change /chek the code for spaces indexes also ***
2)do not give charates as 56-89##13 as you want here only numbers
3) this only for integer if you want to float or double you have to do some changes here
because charters index and length would be difeerent in string.
*/

C++ - How to input space separated numbers into array?

I have this file:
4
10 3 4 6
The first line declares how many numbers the second line has.I want to put the numbers of the second line in an array.So far i have been using this loop to automatically declare how many numbers the second line has and how many times to do the loop:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
ifstream infile;
infile.open("input.in");
string kids;
int x;
int i;
getline(infile,kids);
cout << "The Number Of Kids Is " << kids << endl;
istringstream buffer(kids);
int kidss;
buffer >> kidss;
for(i=0;i<kidss;i++){
infile >> x;
cout << x << " ";
}
infile.close();
return 0;
}
Now i want to do the same thing but instead of inputing the numbers in x i want to put them in an array and then display them as above.Thanks In Advance!
The best way of doing this would be with a std::vector these are variable length arrays in c++.
To use them in this case you would do
std::vector<int> array;
for( int i = 0 ; i < kidss ; ++i ) {
infile >> x;
array.push_back(x);
}
Then if you wanted to print them out again you would be able to do
for( int i = 0 ; i < array.size() ; ++i ) {
std::cout << array[i] << " ";
}