do you know how can I start to count a string from 1 and not from 0 in c++? for example, xyz are on iterations 0,1,2.. but i need them to be on 1,2,3. I know you can put cout << i+1; but is there any other way to do this with strlen(s+1)?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 0; i < n; ++i)
cout<<i<<": "<<s[i]<<"\n";
return 0;
}
i+1 is the way to go. An alternate method is starting your loop with 1 instead and accessing the array at element i-1, but that's a bit silly:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
cin.getline(s, 99);
int n = strlen(s);
for (int i = 1; i <= n; ++i) // i = 1 not 0
cout<<i<<": "<<s[i-1]<<"\n";
return 0;
}
In C++, you shouldn't use C-Strings. Instead, use std::string:
#include <iostream>
#include <string>
int main()
{
std::string s;
std::getline(std::cin, s);
for (int i = 0; i < s.length(); ++i)
std::cout << i + 1 << ": " << s[i] << '\n' ;
return 0;
}
As others have said, the simple answer is really just accept you start from zero - however, for an actually solution you can use boost-range and use an index adaptor with an argument of '1'.
std::string str;
std::getline(std::cin, str);
for (const auto & element : str | boost::adaptors::indexed(1)) {
std::cout << element.index()
<< " : "
<< element.value()
<< std::endl;
}
Related
The user has to enter 3 strings and we have to put them in an array.
Then user enters a char that he wants to find in input strings.
Then if the char is found, update the counter for how many times char appeared.
Example:
User input string: Cat Car Watch
User char input: a
Result:
Letter a appears 3 times!
How can I search through a string array like this to find specific chars?
Code below but I'm stuck:
string userString[3];
for (int i = 0; i < 3; i++)
{
cout << "Input string: ";
getline(cin, userString[i]);
}
char userChar;
cout << "Input char you want to find in strings: ";
cin >> userChar;
int counter = 0;
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
cout << "The char you have entered has appeared " << counter << " times in string array!";
Instead of writing for loops manually it is better to use standard algorithms as for example std::count.
Here is a demonstration program
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = 0;
for ( const auto &s : words )
{
count += std::count( std::begin( s ), std::end( s ), c );
}
std::cout << "count = " << count << '\n';
}
The program output is
count = 3
If your compiler supports C++ 20 then you can write the program the following way
#include <iostream>
#include <string>
#include <iterator>
#include <ranges>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = std::ranges::count( words | std::ranges::views::join, c );
std::cout << "count = " << count << '\n';
}
Again the program output is
count = 3
As for your code then this code snippet
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
is incorrect. You need one more inner for loop to traverse each string as for example
for (int i = 0; i < 3; i++)
{
for ( char c : userString[i] )
{
if ( c == userChar)
{
counter++;
}
}
}
I want to create a string with numbers. So i define length of my string array to 10, but when i start the program in console is 11 chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 10
using namespace std;
int main()
{
srand(time(0));
int numArr[N];
for(int i = 0; i < N; i++)
numArr[i] = rand() % 26 + 97;
for(int i = 0; i < N; i++)
std::cout << numArr[i] << " ";
std::cout << std::endl;
char str[N] = "";
for(int i = 0; i < N; i++)
str[i] = numArr[i];
std::cout << str << endl;
std::cout << strlen(str);
return 0;
}
A string needs to be terminated with \0 to get its length with strlen, in the codestr isn't terminated with \0, when you add it as last character strlen gives correct answer
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 10
using namespace std;
int main()
{
srand(time(0));
int numArr[N];
for(int i = 0; i < N; i++)
numArr[i] = rand() % 26 + 97;
for(int i = 0; i < N; i++)
std::cout << numArr[i] << " ";
std::cout << std::endl;
char str[N + 1] = "";
for(int i = 0; i < N; i++)
str[i] = numArr[i];
str[N] = '\0'; // terminate with \0
std::cout << str << endl;
std::cout << strlen(str);
return 0;
}
It is rather risky to use char[N] when you can use std::string.
Here is safer way to write your code (and you will now get the 10 characters lenght you expect).
int main()
{
srand(time(0));
char numArr[N]; // I changed your type from int to char because you can only pack chars in a string
for(char i = 0; i < N; i++)
numArr[i] = (char)(rand() % 26 + 97);
for(int i = 0; i < N; i++)
std::cout << numArr[i] << " ";
std::cout << std::endl;
std::string str;
str.reserve(N); // not strictly required: this is an optimization
for(int i = 0; i < N; i++)
str.push_back(numArr[i]);
std::cout << str << endl;
std::cout << str.length();
return 0;
}
I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}
Ok I've been looking everywhere and I can't find the proper way to do this. I simply want to take in a string, put that string in the array and output the contents. However, I want to do it dependent on the size of the string which the user enters in. And I was getting weird errors such as incompatibility and I would like to know why please, thank you.
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y);
array<char, strlen(y)>state;
for(int i=0; i<strlen(y); ++i)
cout << state[i] << ' ';
system("PAUSE");
return 0;
}
std::array needs a compile-time size, so cannot be instantiated with strlen. Furthermore, strlen does not work with std::string, it expects a pointer to char, pointing to the beginning of null terminated string.
You could use an std::vector<char> instead:
std::string y;
std::cout << "Enter value";
std::getline(std::cin, y);
std::vector<char> state(y.begin(), y.end());
for(int i = 0; i < state.size(); ++i)
std::cout << state[i] << ' ';
On the other hand, why not just use the string y directly? Do you really need the "array"?
for(int i = 0; i < y.size(); ++i)
std::cout << y[i] << ' ';
std::array is a wrapper template class around a C static array. This means that it's dimensions must be known at build time (not runtime).
Here's a short version of a working code that's also a little faster since string::length() is called once.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( size_t i = 0, yLen = y.length(); i < yLen; ++i )
cout << y[i] << ' ';
system( "PAUSE" );
return 0;
}
If you like pointer tricks and take advantage that string's buffer is contiguous in memory (by the C++ standard) your code can look like:
int main()
{
string y;
cout << "Enter value";
getline(cin, y );
for( const char* p = &y[0]; *p; ++p )
cout << *p << ' ';
system( "PAUSE" );
return 0;
}
i hope it will work..
#include "stdafx.h"
#include <iostream>
#include <array>
#include <string>
using namespace std;
int main()
{
int x = 4000;
string y;
cout << "Enter value";
getline(cin, y );
char *b = new char[y.length()];
int j=y.length();
//array< char, strlen(y)>state;
for( int i = 0; i<j; ++ i )
{//whatever uu want
}
//cout << state[i] << ' ' ;
system( "PAUSE" );
return 0;
}