Here is my code:
#include<stdio.h>
int main()
{
int a = '\0';
while ((a = getchar()) != EOF){
if (a != ' ' || a != '\t' || a != '\n' || a != ';' || a != ',' || a != '.'){
putchar(a);
}
else{
continue;
}
}
system("pause");
return 0;
}
I need to read a poem from an input file, and output the poem with no spaces or punctuation. Must be done using I/O variation. I've searched all over, but I can't seem to find how to do this the way I need. Any help is much appreciated...
Hope this solves your Problem. Use ascii values for character. Also use fgetc/fputc/fscanf/fprintf etc for file i/o related operations. ASCII CHART link here ASCII Chart VALUES.
#include<stdio.h>
int main()
{
FILE *pfile=NULL;
char data[255];
int i=0;
pfile=fopen("poem.txt","r");
while((data[i]=fgetc(pfile)) != EOF)
{
if(data[i]> 32 && data[i] < 123)
{
if(data[i] != 44 && data[i]!= 45 && data[i]!=46 && data[i]!=33)
{
//In the above 'if statement' you can add more characters/special
//characters you wish to exclude/ignore
printf("%c",data[i]);
i++;
}
}
}
return 0;
}
Related
I got an error on second if
Making the exactly same if outside of for seems to work just fine, it returns the value from priority function, but when I try to do it in for it said that I'm trying to pass an invalid parameter to a function which considers it to be fatal.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char c);
int main()
{
stack<char>Operator;
string input;
string output;
getline(cin, input);
for (int i = 0; i < input.size(); i++)
{
if (input[i] == '(' || input[i] == ')' || input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/')
Operator.push(input[i]);
else
output.push_back(input[i]);
if (priority(Operator.top()) == 3)
{
int aux = Operator.top();
Operator.pop();
while (priority(Operator.top() == 4))
{
output.push_back((char)Operator.top());
Operator.pop();
}
Operator.push(aux);
}
if (priority(Operator.top() == 2))
{
Operator.pop();
while (priority(Operator.top()) != 1)
{
output.push_back(Operator.top());
Operator.pop();
}
Operator.pop();
}
}
cout << output;
cin.ignore();
cin.get();
return 0;
}
int priority(char c)
{
if (c == '(')
return 1;
if (c == ')')
return 2;
if (c == '+' || c == '-')
return 3;
if (c == '*' || c == '/')
return 4;
}
The statement Operator.top() is being called on every symbol in the input string. That would probably work in case your string starts with a '(' symbol or with a unary plus, but what would happen in case of "2*2"?
As a perfect solution you should redesign your code to make it a finit automaton. As a simple ad hoc fix you should check if the current symbol is an operation or digit and don't call the Operator.top() in the latter case:
if (isdigit(input[i])) {
output.push_back(input[i]);
}
else {
Operator.push(input[i]);
if (priority(Operator.top()) == 3) {
// ...
}
// ...
}
Ok, so I'm working on a project that requires us to translate English to Pig Latin. I was trying to kind of copy and tweak some code I found online that did the opposite because the functions kind of looked similar. In my class, we are given certain functions that have to be implemented in our code.
This has to be present in my source code:
struct Word
{
string english;
string pigLatin;
};
Function 1: Word * splitSentence(const string words, int &size); ~ Takes the English sentence as 1 string
Function 2: void convertToPigLatin(Word [] wordArr, int size); ~ Converts English to Pig Latin
Function 3: void convertToPigLatin(Word [] wordArr, int size); ~ Display
Here is the code that I have.
Edit: The problem I'm having is that I don't have wordArr declared anywhere in my code so it can't compile. I also noticed a few minor errors and changed my code a little. You'll have to excuse me I'm very tired right now.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
struct Word
{
string english;
string pigLatin;
};
Word * splitSentence(wordArr&; int &);
void convertToPigLatin (Word[], int);
void displayPigLatin (Word[], int);
int main()
{
string userInput;
int size;
cout <<"This is an English to Pig Latin translator.\n";
cout <<"Enter a sentance that you want to translate.\n";
getline(cin, userInput);
Word *wordArr = convertToPigLatin(userInput, size);
displayPigLatin(wordArr, size);
return 0;
}
Word * splitSentence(const Word [] wordArr, int &size)
{
int num = 0;
int phraseLength = userInput.length();
for (int i = 0; i < size; i++)
{
if (isspace(userInput[i]))
{
if (isspace(userInput[ i - 1]))
{
num--;
}
num++;
}
}
if (ispunct(userInput[i]))
{
if (i != (phraseLength - 1))
{
userInput.erase(1--, 1)
}
}
}
void convertToPigLatin(Word wordArr[], int size)
{
for (int i = 0; i < size; i++)
{
int stringLength;
if (i == (size - 1))
{
stringLength = wordArr[i].userInput.length();
}
else
{
stringLength = wordArr[i].userInput.length() - 1;
}
string vowel, way;
vowel = wordArr[i].userInput.at(stringLength - stringLength);
way = wordArr[i].userInput.at(stringLength - 3);
bool markV = ((vowel == 'A') || (vowel == 'a') (vowel == 'E') || (vowel == 'e')
(vowel == 'I') || (vowel == 'i') (vowel == 'O') || (vowel == 'o')
(vowel == 'U') || (vowel == 'u'));
wordArr[i].userInput.erase(stringLength - 3, 3);
if (!(markV && (way == 'w')))
{
wordArr[i].english = way + wordArr[i].userInput;
}
}
displayPigLatin(wordArr, stringLength);
}
void displayPigLatin(const Word wordArr[], int size);
{
cout << "\nHere is your phrase in PigLatin: ";
for (int i = 0 i < size; i++)
{
cout << wordArr[i].userInput << " ";
}
}
Important Note: You can only use range based for-loops in C++11 or higher if your compiler doesn't support C++11 or higher, use regular for-loops...
Given your question, you have to use this structure (It is equivalent to the one in the question):
typedef struct
{
std::string english;
std::string pig_latin;
} Word;
This is a macro which is going to be used to check if the first letter is a vowel or a consonant (Hence, !IS_VOWEL(some_char))...
#define IS_VOWEL(x) ((x) == 'A' || (x) == 'E' || (x) == 'I' || (x) == 'O' || (x) == 'U' || \
(x) == 'a' || (x) == 'e' || (x) == 'i' || (x) == 'o' || (x) == 'u')
Another function which we need to acquire only the part of the word which has letters (not symbols and numbers):
std::pair<unsigned, unsigned> GetWord(std::string word)
{
auto start = word.end();
for (auto it = word.begin(); it != word.end(); ++it)
if (tolower(*it) >= 'a' && tolower(*it) <= 'z' && start == word.end())
start = it;
else if (start != word.end() && !(tolower(*it) >= 'a' && tolower(*it) <= 'z'))
return std::make_pair(std::distance(word.begin(), start), std::distance(word.begin(), it));
return std::make_pair(start == word.end() ? 0 : std::distance(word.begin(), start), std::distance(word.begin(), word.end()));
}
And last but not least, the function to convert English to Pig-Latin (I know it is huge):
std::vector<Word> CreatePigLatinWordsFromEnglish(std::string english, bool sentence_case = true)
{
// You can break it from here to use inside another function (viz., splitSentence)
std::transform(english.begin(), english.end(), english.begin(), ::tolower);
std::stringstream english_stream(english);
std::vector<Word> words;
std::string temporary;
while (std::getline(english_stream, temporary, ' '))
words.emplace_back(Word({ temporary, "" }));
// Till here...
// From here the conversion starts...
for (auto &word : words)
{
auto const word_it = GetWord(word.english);
if (!IS_VOWEL(word.english[word_it.first]) && !std::string(std::next(word.english.begin(), word_it.first),
std::next(word.english.begin(), word_it.second)).empty())
{
word.pig_latin.append(std::string(word.english.begin(), std::next(word.english.begin(), word_it.first)));
word.pig_latin.append(std::string(std::next(word.english.begin(), word_it.first + 1), std::next(word.english.begin(), word_it.second)));
word.pig_latin.append(1, word.english[word_it.first]);
word.pig_latin.append(std::string("ay"));
word.pig_latin.append(std::next(word.english.begin(), word_it.second), word.english.end());
}
else
word.pig_latin = std::string(word.english.begin(), std::next(word.english.begin(), word_it.second)) + "way"
+ std::string(std::next(word.english.begin(), word_it.second), word.english.end());
}
// Conversion ends here...
// Changing the case from lower case to sentence case if needed...
if (sentence_case)
{
words[0].english[0] = toupper(words[0].english[0]);
words[0].pig_latin[0] = toupper(words[0].pig_latin[0]);
}
return words; // Returning the list of words we got...
}
Well, an example to demonstrate this method:
int main()
{
auto const test = "An apple a day keeps the doctor away!";
for (auto word : CreatePigLatinWordsFromEnglish(test))
std::cout << word.pig_latin << " ";
return 0;
}
Output:
Anway appleway away ayday eepskay hetay octorday awayway!
Try it out and see whether it gives you the required result...
Kind regards,
Ruks.
I'm writing a program in C++ that can take several input arguments like so:
Edit: based on suggestions from comments
int main(int argc, char **argv) {
constants c;
for (int i=0; i<argc; i++) {
if ( (argv[i])[0] == '-') {
if ((argv[i])[1] == 'h'){
bHelp = true;
//spit out some help text here
}
else if ((argv[i])[1] == 'c' && (argv[i+1]) != nullptr){
c.host = argv[i+1];
}
else if ((argv[i])[1] == 'd' && (argv[i+1]) != nullptr){
c.databasename = argv[i+1];
}
else if ((argv[i])[1] == 'w' && (argv[i+1]) != nullptr){
c.password = argv[i+1];
}
else if ((argv[i])[1] == 'u' && (argv[i+1]) != nullptr){
c.username = argv[i+1];
}
else if ((argv[i])[1] == 'p' && (argv[i+1]) != nullptr){
c.port = argv[i+1];
}
}
}
if (bHelp) {exit(1);}
When run the program seems to work properly, so far so good I thought.
However if any of the input following the flags has special characters for instance a '#' the program segfaults on start.
Whilst you can still make it work by manually escaping such characters on start, with "./app -u testuser -w \#fakepass" for example.
I would rather not bother my end-user with such things and would prefer to solve it in the code.
I am using the following code to break apart a line of text.
A line of text, such as
"adduser john -u 2001 -g 1002 -p john123 -c Project Work"
is passed to the constructor.
I am trying to separate the text by the commands "-u, -g, -p, -c"
"john" will be saved as name,
"2001" will be saved as UID,
"1002" will be saved as GID, etc.
AccountInfo::AccountInfo(char* line){
_line = line;
char bufferLine[256];
unsigned int length1 = 0;
unsigned int tempLength1 = 0;
//find length of line of text
while (_line[length1] != '\0'){
length1++;
}
//separate the text by white space
// start at 8 because adduser is not a command
for (int i = 8; i < length1 + 1; i++){
bufferLine[tempLength1 + 1] = '\0';
printf(bufferLine);
if (_line[i] == ' ')
{
if (bufferLine[0] == '-')
{
//test only u and c commands for now
if (bufferLine[1] == 'u'){
bufferLine[0] = '\0'; //clear contents of array
tempLength1 = 0;
while (!_line[i] == '-'){
bufferLine[tempLength1] = _line[i];
i++;
tempLength1++;
}
bufferLine[tempLength1] = '\0';
printf(bufferLine);
printf("\n This is UID \n");
setUID((unsigned int)bufferLine);
}
else if (bufferLine[1] == 'c'){
bufferLine[0] = '\0';
tempLength1 = 0;
while (!_line[i] == '\0'){
bufferLine[tempLength1] = _line[i];
i++;
tempLength1++;
}
bufferLine[tempLength1] = '\0';
printf(bufferLine);
printf("\n this is gecos \n");
setGecos(bufferLine);
}
}
else{
//is name
bufferLine[tempLength1] = '\0';
setName(bufferLine);
printf("\n I am the user's name\n");
printf(bufferLine);
printf("\n");
}
bufferLine[0] = '\0'; //reset buffer line
tempLength1 = 0; // reset incrementation for buffer line
}
else{
bufferLine[tempLength1] = _line[i];
tempLength1++;
}
}
}
I am working on functionality of the -u command. It reaches the
if (bufferLine[1] == 'u') portion of the code, but always bypasses the while loop following it
while (!_line[i] == '-') I have tried changing the '-' to exit the while loop with ' ' and even any letter 'a' 'g' 'd', however nothing works except '\0'. This is only acceptable for the -c command, as everything after it should be printed.
The -c command works as it should, as does saving the name. However, none of the other commands will work because it does not make it to the loop.
I have been thinking about this problem for a while and I believe it should work, however the code never makes it through the while loop. Is there a problem with the syntax? Or is there something I am missing about nested loops?
Thanks
This expression
while (!_line[i] == '-'){
evaluates as (see operator precedence):
while ((!(_line[i])) == '-') { // because ! has higher precedence than ==
while (false == '-') { // because _line[i] == ' ', !' ' is false
while (false) {
You probably meant
while (_line[i] != '-') {
while (!_line[i] == '-') is essentially while ((!_line[i]) == '-') (note the operators precedence).
What you possibly want is while (! (_line[i] == '-')) { or, simpler, while (_line[i] != '-'){.
!_line[i] == '-'
! has lower precedence than == and is evaluated as
(!_line[i]) == '-'
and this will never be true
http://en.cppreference.com/w/cpp/language/operator_precedence
I attended a quiz, I gave the code but the auto-test shows that one of the eight test cases failed.
I myself tested my code many times, but all passed. I can't find where is the problem.
The question is to design a algorithm to check whether the brackets in a string match.
1) Just consider rounded brackets () and square brackets [], omit ohter chars.
2) Each pair brackets should match each other. That means ( matches ), and [ matches ].
3) Intercrossing is not allowed, such as : ([)]. There are two pairs of brackets, but they intercross each other.
To solve the problem, my method is described as follows:
Search each char in the whole input string, the index from 0 to str.size() - 1.
Use two stacks to record the opening tag (, and [, each type in one stack. When encountering one of them, push its index in the corresponding stack.
When encouterning the closing tag ) and ], we pop the corresponding stack.
Before popping, check the top of two stacks, the current stack should have the max index, otherwise that means there are unmatched opening tag with the other type, so the intercrossing can be checked this way.
My Code is Here:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string str;
cin >> str;
stack<int> s1, s2;
int result = 0;
for (int ix = 0, len = str.size(); ix < len; ix++)
{
if (str[ix] == '(')
{
s1.push(ix);
}
else if (str[ix] == '[')
{
s2.push(ix);
}
else if (str[ix] == ')')
{
if (s1.empty() || (!s2.empty() && s1.top() < s2.top()))
{
result = 1;
break;
}
s1.pop();
}
else if (str[ix] == ']')
{
if (s2.empty() || (!s1.empty() && s2.top() < s1.top()))
{
result = 1;
break;
}
s2.pop();
}
else
{
// do nothing
}
}
if (!s1.empty() || !s2.empty())
{
result = 1;
}
cout << result << endl;
}
As methoned before, this question can be solved by just on stack, so I modified my code, and here is the single stack version. [THE KEY POINT IS NOT TO ARGUE WHITCH IS BETTER, BUT WHAT'S WRONG WITH MY CODE.]
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string str;
cin >> str;
stack<char> s;
const char *p = str.c_str();
int result = 0;
while (*p != '\0')
{
if (*p == '(' || *p == '[')
{
s.push(*p);
}
else if (*p == ')')
{
if (s.empty() || s.top() != '(')
{
result = 1;
break;
}
s.pop();
}
else if (*p == ']')
{
if (s.empty() || s.top() != '[')
{
result = 1;
break;
}
s.pop();
}
else
{
// do nothing
}
p++;
}
if (!s.empty())
{
result = 1;
}
cout << result << endl;
}
When using formatted input to read a std::string only the first word is read: after skipping leading whitespate a string is read until the first whitespace is encountered. As a result, the input ( ) should match but std::cin >> str would only read (. Thus, the input should probably look like this:
if (std::getline(std::cin, str)) {
// algorithm for matching parenthesis and brackets goes here
}
Using std::getline() still makes an assumption about how the input is presented, namely that it is on one line. If the algorithm should process the entire input from std::cin I would use
str.assign(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>());
Although I think the algorithm is unnecessary complex (on stack storing the kind of parenthesis would suffice), I also think that it should work, i.e., the only problem I spotted is the way the input is obtained.