英文:
Is there a way to use a tolower() like function on a vector<string> variable in C++?
问题
I'm trying to load and sort a file alphabetically. To make this easier, I have to convert the characters to lowercase.
Now, do I have to do this character-by-character as I read it into a string array (because tolower()
only accepts characters), or can I somehow use it with a vector<string>
container?
Here's the code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
int main() {
ifstream file("phoneNumbers.txt");
vector<string> wordStream;
int i = 0;
if (file.fail()) {
cout << "Couldn't open file!";
return 1;
}
while(file >> wordStream[i]) {
wordStream[i] = tolower(wordStream[i]);
++i;
}
}
Newbie question, I know.
I already tried the std::transform()
function that someone recommended on StackOverflow, but still it didn't work.
英文:
I'm trying to load and sort a file alphabetically. To make this easier, I have to convert the characters to lowercase.
Now, do I have to do this character-by-character as I read it into a string array (because tolower()
only accepts characters), or can I somehow use it with a vector<string>
container?
Here's the code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
int main() {
ifstream file("phoneNumbers.txt");
vector<string> wordStream;
int i = 0;
if (file.fail()) {
cout << "Couldn't open file!";
return 1;
}
while(file>>wordStream[i]) {
wordStream[i] = tolower(wordStream[i]);
++i;
}
}
Newbie question, I know.
I already tried the std::transform()
function that someone recommended on StackOverflow, but still it didn't work.
答案1
得分: 3
你的代码有两个问题,`tolower` 在字符串上不起作用,并且你的向量大小为零,所以对于任何`i`的值,`wordStream[i]`都会报错。以下是修复了这些错误的代码:
string temp;
while (file >> temp) { // 读入一个临时字符串
// 将字符串转换为小写
std::transform(temp.begin(), temp.end(), temp.begin(), tolower);
// 将临时字符串添加到向量中
wordStream.push_back(temp);
}
英文:
Your code has two problems, tolower
doesn't work on strings, and your vector has a size of zero so wordStream[i]
is an error for any value of i
. Here's the code fixed of those errors
string temp;
while (file >> temp) { // read to a temporary string
// convert string to lower case
std::transform(temp.begin(), temp.end(), temp.begin(), tolower);
// add temporary string to vector
wordStream.push_back(temp);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论