Currently I am working on a problem to reformat the inputted string into the odd char then even char with no newline. ex. Input: Good Test. Ouput: Go etodTs. For some reason when I run the program it only outputs a "G".
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
using namespace std;
int main (int argc, char ** argv) {
char sWordOdd[100] = {0};
scanf("%s", sWordOdd);
int iNum = strlen(sWordOdd);
for (int i=0; i<=iNum && i%2==0; i++) {
printf("%c",sWordOdd[i]);
}
for (int a=0; a<=iNum && a%2!=0; a++) {
printf("%c",sWordOdd[a]);
}
printf("\n");
return 0;
}
Your i<=iNum && i%2==0 break condition terminates your loop early. To achieve the effect you want, put an if statement inside the loop, like so:
for (int i = 0; i <= iNum; i++){
if(i % 2 == 0)
printf("%c",sWordOdd[i]);
}
As for your second loop, I think you meant a++ instead of a--, because otherwise you'll try to access the array using a negative index. I think you meant for your loop to look like this:
for (int a = 0; a <= iNum; a++){
if(a % 2 != 0)
printf("%c",sWordOdd[a]);
}
Side note: Notice the spacing between the variables and the operators in my code. Using spaces like this makes your code easier to read.
int main()
{
string line;
getline(cin, line);
for (size_t start : {0,1})
for (size_t ii = start; ii < line.size(); ii += 2)
cout << line[ii];
cout << endl;
}
The above code handles arbitrarily long lines, is C++11 rather than C, and works.
As said before the loops terminate if i<=iNum && i%2==0 is true (for the first loop), which is the case for i=0. The second loop terminates with i=1.
Since you want to iterate all characters you have to move the i%2==0 part out of the for-statement:
for (int i=0; i<=iNum; i++) {
if (i%2==0)
{
printf("%c",sWordOdd[i]);
}
}
The second loop needs to be modified in the same way...
To fix this problem you have to use a function that can see stuff after whitespaces. This function is called getline. But with getline, you have to use string, so in this example I used string. I then found the size with the .size() function and then using just one constraint for the for loop instead of two in the question. I also took off the char array and replaced it with string as stated above. Everything else is pretty much the same. Using this answer lets me not having to use cstring and also simplifying my code into a short, easy way that is easy to follow through.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
using namespace std;
int main (int argc, char ** argv)
{
string sWordOdd;
getline(cin, sWordOdd, '\n');
int iNum = (int)sWordOdd.size();
for (int i=0; i<iNum; i+=2){
cout << sWordOdd[i];
}
for (int a=1; a<iNum; a+=2){
cout << sWordOdd[a];
}
printf("\n");
return 0;
}
Related
Hi I'm trying to make a program that takes a sum as an input lets say 1+2+3+2+2+1 and must sort the sum out as 1+1+2+2+2+3
this is the code
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
string s;
char w[100];
char x[100];
cin>>s;
//moving string s to array w to remove the '+' charachter for sorting
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
//sorting array w
sort(w,w+100);
//moving array w to array x and re-adding the '+' after sorting
for (int y=0; y > s.size();y++){
w[y]==x[y];
x[y+1]=='+';
}
cout<<x;
return 0;
}
but when i run it, it gives me a blank output
this is my first time at a c++ program im still a beginner at it
thanks for the help in advance!
I can see that you are new to the language, as you lack some understanding of basic concepts. I will first give you some tips and explanation on your mistakes, then I'll give you a more suitable solution.
First of all, try avoiding using C-styled arrays like you do with w and x. They are prone to errors because of no bounds checking, look into using std::vector or std::array instead.
== and = are NOT the same! == is used when comparing two things and = is used for assigning the right side to the left side.
Your loops are completely wrong, using
for (int i=0; i>s.size() ;i++)
will never even enter the loop. Use i < s.size() of course. I also recommend using ++i instead of i++ but that is not too important.
Your "thinking in code" is sometimes weird too
for (int i=0; i>s.size() ;i++){
if (s.at(i) = '+')continue;
else s.at(i) == w[i];
}
(not minding the > and = mistakes), why not check if it is not '+' instead of continueing and then doing something?
this code should logically be
for (int i=0; i>s.size() ;i++){
if (s.at(i) != '+') s.at(i) == w[i];
}
Last but not least, try to be consistent. First you use i as loop variable and the second time you use y. Not that it matters, but consistency is always good when coding.
I made a quick solution for your problem:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string input;
cin >> input;
vector<int> nrs = vector<int>(); //initialising this is not really needed
for (char c : input) //range based for loop, prevents mistakes with indices
{
if (c != '+')
{
nrs.push_back(c - '0'); // a char minus '0' gives the numerical value
}
}
sort(nrs.begin(), nrs.end());
string answer;
for (int nr : nrs) //range based for loop again
{
answer += to_string(nr); //use to_string to convert an int to a string
if (nr != nrs.back()) //to avoid adding the '+' after the last character
{
answer += '+';
}
}
cout << answer << endl;
return 0;
}
I have written a small program in c++ that will take as an input a string. It will then print the first non-repeated character in the string. Below is my code. This is for a challenge on CodeEval.com. The thing is, as far as I can tell, the code works as it's supposed to. But CodeEval.com tells me my code is not correct. Unfortunately, I'm not allowed to see the input they're using, but when used at home, I see no problem. Can anyone tell me if there's anything about my code that does not fit the prompt?
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string input = "";
while(getline(cin, input)){
vector<char> inputVector(input.begin(),input.end());
char firstNonRepeatedChar;
for(int i = 0; i < inputVector.size(); i++){
if((inputVector[i] != inputVector[i + 1]) && (inputVector[i] != inputVector[i - 1])){
firstNonRepeatedChar = inputVector[i];
break;
}
}
cout << firstNonRepeatedChar << "\n";
}
//system("PAUSE");
return EXIT_SUCCESS;
}
EDIT:
This is the code that gave me the right answer, if anyone is wondering. Ben helped me realize that I wasn't answering the question properly based on the prompt.
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int findCharInVector(vector<char>& input, char charToFind);
int main(int argc, char *argv[])
{
string input = "";
while(getline(cin, input)){
vector<char> characters(input.begin(),input.end());
char firstNonRepeatedChar;
for(int i = 0; i < characters.size(); i++){
if(!(findCharInVector(characters, characters[i]) > 1)){
firstNonRepeatedChar = characters[i];
break;
}
}
cout << firstNonRepeatedChar << "\n";
}
//system("PAUSE");
return EXIT_SUCCESS;
}
int findCharInVector(vector<char>& input, char charToFind){
int output = 0;
for(int i = 0; i < input.size(); i++){
if(input[i] == charToFind){
output++;
}
}
return output;
}
Based on the link in the comments, a non-repeated character is one that only appears in the string once. Here is the example given:
yellow // y
tooth // h
Your code:
if((inputVector[i] != inputVector[i + 1]) && (inputVector[i] != inputVector[i - 1])){
firstNonRepeatedChar = inputVector[i];
Is only checking if a character is not repeated consecutively. If it was the way you are thinking, then the example above tooth, the first non-repeated would be t, not h as the example specifies.
Furthermore inputVector[i] != inputVector[i - 1] will cause undefined behavior for i == 0.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
using namespace std;
int gradeExam(string answerKeyARR[]);
int main()
{
const int QUESTIONS = 10;
const int MAX_STUDENTS = 250;
ifstream inFile;
ofstream outFile;
inFile.open("grade_data.txt");
outFile.open("grade_report.txt");
string ansKey;
inFile >> ansKey;
string answerKeyARR[QUESTIONS];
//Loop for storing each answer into an array rather than all in a single string.
for (int j = 0; j < QUESTIONS; j++)
{
answerKeyARR[j] = ansKey.substr(j,1);
}
int i = 0;
int numStudents = 0;
string studentAnswers[MAX_STUDENTS];
//Loop to read in all answers into array and count number of students.
while (!inFile.eof())
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
//WHY DOES IT CRASH HERE?!
string studentAnswersARR[numStudents][QUESTIONS];
for (int k = 0; k < numStudents; k++)
{
for (int l = 0; l < QUESTIONS; l++)
{
studentAnswersARR[k][l] = studentAnswers[l].substr(l,1);
cout << studentAnswersARR[k][l];
}
}
inFile.close();
outFile.close();
return 0;
}
Okay, so basically once it gets to the part where it's removing the substring, it crashes. It works perfectly fine for retrieveing the answerkey answers, so why the hell is it crashing when it gets to this point? This is still a WIP for basic coding 2.
Also, when I change variable 'l' to, say, position 0, it works. What gives?
There are multiple issues with your code that may cause problems.
First, your input loop is not bounded properly. It should stop at MAX_STUDENTS, but you fail to check for this limit.
Second, do not use eof() to check for the end of file. There are many posts on SO discussing this.
while (!inFile && i < MAX_STUDENTS)
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
The next issue is the line you highlighted in your question. It probably crashes due to stack space being exhausted. But the code you have uses a non-standard C++ extension, and once you do that, then the rule as to what that line really does internally is up to the compiler vendor.
So to alleviate this with using standard C++, the following can be done:
#include <vector>
#include <string>
#include <array>
//...
std::vector<std::array<std::string, QUESTIONS> >
studentAnswersARR(numStudents);
So, I am trying to read a string from cin, then loop through the string to count which characters in that string are actually letters in the English alphabet. I have wrote a program that works just fine, but I want to know if there is a more efficient way of doing this, without looping through the entire English alphabet.
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(int i = 0; i < my_str.length(); i++){
for(int j = 0; j < alphabet.length(); j++){
if (tolower(my_str.at(i)) == alphabet.at(j)){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
}
cout << countOfLetters;
return 0;
}
EDIT: Here is my new and improved code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(unsigned int i = 0; i < my_str.length(); i++){
if (isalpha(my_str.at(i))){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
cout << countOfLetters;
return 0;
}
enter code here
Use isalpha() to see which characters are letters and exclude them.
So, you could modify your code like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str;
getline(cin, my_str);
int countOfLetters = 0;
for (size_t i = 0; i < my_str.length(); i++) { // int i produced a warning
if (isalpha(my_str.at(i))) { // if current character is letter
++countOfLetters; // increase counter by one
}
}
cout << countOfLetters;
return 0;
}
You could perhaps use isalpha:
for(int i = 0; i < my_str.length(); i++)
if (isalpha(my_str.at(i))
countOfLetters++;
You can use the std::count_if() algorithm along with the iterator interface to count characters for which some predicate returns true. The predicate can use std::isalpha() to check for alphabetical characters. For example:
auto count = std::count_if(std::begin(str), std::end(str),
[&] (unsigned char c) { return std::isalpha(c); });
You could also check if the int cast is between 65-90 or 97-122
at example
(int)'a'
Should give 97
This will be the most performant method without any doubt.
Its better than using isalpha().
Check http://www.asciitable.com/ for ASCI Numbers
isalpha works well for this particular problem, but there's a more general solution if the list of characters to accept wasn't so simple. For example if you wanted to add some punctuation.
std::set<char> good_chars;
good_chars.insert('a'); good_chars.insert('A');
good_chars.insert('b'); good_chars.insert('B');
// ...
good_chars.insert('z'); good_chars.insert('Z');
good_chars.insert('_');
// the above could be simplified by looping through a string of course
for(int i = 0; i < my_str.length(); i++){
countOfLetters += good_chars.count(my_str[i]);
}
I'm doing a Caesar block cypher. The general steps to a solution are:
Read your message into a large buffer or a string object.
Either remove the spaces and punctuation or not (it's harder for the
Enemy to read if you do).
Then count the chars in the message.
Pick the first perfect square greater than the message length,
allocate an array of char that size.
Read the message into a square array of that size from left to right,
top to bottom.
Write the message out top to bottom, left to right, and you've
encyphered it.
My Code:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <ctype.h>
#include <cmath>
#include <functional>
#include <numeric>
#include <algorithm>
#include <locale>
using namespace std;
int main(int argc, char *argv[])
{
int length = 0;
cout << "Enter a string: ";
string buffer;
char buff[1024];
while (getline(cin, buffer))
{
buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
break;
}
length = buffer.length();
int squareNum = ceil(sqrt(length));
strcpy(buff, buffer.c_str());
char** block = new char*[squareNum];
for(int i = 0; i < squareNum; ++i)
block[i] = new char[squareNum];
int count = 0 ;
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
block[i][j] = buff[count++];
}
}
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
cout.put(block[j][i]) ;
}
}
return 0;
}
For the most part, it works. The problem I get is when there's more than one line of input.
Ex. 1
this is sample text suitable for a simulation of a diplomatic mission or a spy's instructions
Ex. 2
this is sample text suitable
for a simulation of a diplomatic
mission or a spy's instructions
Example 1 works and example 2 does not because there are multiple lines. I have a feeling it has to do with the while(getLine) function but I don't know exactly what to change.
This "break" inside the "while" loop - it breaks the loop after the first "getline" call. That's why you get only one line.
May be you should consider removing break after erase.
What you do in here:
while (getline(cin, buffer))
{
buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
break;
}
is saving new line to buffer every time you use getline. I mean, each time there is getline() evoked your buffer is being replaced, not appended.
Try this:
string buffer = "";
string buff2;
// You need to provide some way to let the user stop the input
// e.g. ask him to declare number of lines, or what I recommend
// check for an empty line given, which is implemented below:
while (getline(cin, buff2))
{
// now pressing [enter] after the last input line stops the loop
if (buff2.empty())
break;
buff2.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(::isalnum))), buffer.end());
buffer += buff2;
}