所以我試圖將檔案中的字串資料讀取到動態分配的陣列中,但我似乎無法獲得正確的代碼。我在下面的代碼中使用了一個預設大小的陣列,但這效率不高,因此我想使用動態記憶體分配。我知道我必須使用指標,但我對這個概念還很陌生,所以任何幫助都將不勝感激。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <string>
#define SIZE 100
using namespace std;
void loadData();
int main()
{
loadData();
return 0;
{
string fileName;
std::string wordArray[SIZE];
cout << "Please enter the name of the text file you want to process followed by '.txt': " << endl;
cin >> fileName;
ifstream dataFile(fileName);
if (dataFile.fail()) {
cerr << fileName << " could not be opened." << endl; //error message if file opening fails
exit(-1);
}
while (!dataFile.eof()) {
for (int i = 0; i < SIZE; i ) {
dataFile >> wordArray[I];
for (std::string& s : wordArray) //this for loop transforms all the words in the text file into lowercase
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::tolower(c); });
}
}
dataFile.close();
}
}
uj5u.com熱心網友回復:
在下面從input.txt的檔案程式說明如何存盤字串讀取并以小寫存盤在std::vector。
版本 1:逐字(小寫)存盤到向量中
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <sstream>
int main()
{
std::ifstream inputFile("input.txt");
//create vector that will contain the words in the file in lowercase
std::vector<std::string> wordVec;
std::string line, individualWord;
if(inputFile)
{
while(std::getline(inputFile, line, '\n'))
{
std::istringstream ss(line);
while(ss >> individualWord)//word by word
{
std::transform(individualWord.begin(), individualWord.end(), individualWord.begin(),
[](unsigned char c)
{ return std::tolower(c);
});
wordVec.push_back(individualWord);
}
}
}
else
{
std::cout<<"file could not be opened"<<std::endl;
}
inputFile.close();
//lets print out the elements of the vector to check if elements are correctly stored in lowercase
for(const std::string &elem: wordVec)
{
std::cout<<elem<<std::endl;
}
return 0;
}
版本 1 的輸出可以在這里看到。
版本 2:將完整的單行(小寫)存盤到向量中
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
int main()
{
std::ifstream inputFile("input.txt");
//create vector that will contain the words in the file in lowercase
std::vector<std::string> wordVec;
std::string line;
if(inputFile)
{
while(std::getline(inputFile, line, '\n'))
{
std::transform(line.begin(), line.end(), line.begin(),
[](unsigned char c)
{ return std::tolower(c);
});
wordVec.push_back(line);
}
}
else
{
std::cout<<"file could not be opened"<<std::endl;
}
inputFile.close();
//lets print out the elements of the vector to check if elements are correctly stored in lowercase
for(const std::string &elem: wordVec)
{
std::cout<<elem<<std::endl;
}
return 0;
}
上面(版本 2)程式的輸出可以在這里看到。
版本 1 和版本 2之間的區別在于版本 1 讀取完整行,然后逐字讀取并將這些單詞(小寫)存盤到std::vector版本 2 讀取完整行(以 '\n' 結尾)并存盤行(小寫)到std::vector.
uj5u.com熱心網友回復:
有時生活可能很容易。通過使用現代 C 元素,最終實作將非常簡單。
我不太確定我應該為 3 行代碼解釋什么。基本上可以通過代碼中的注釋看到。
請看第一個解決方案:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cctype>
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputStream{ "r:\\input.txt" }; inputStream) {
// Define a vector and read all words from the file
std::vector words(std::istream_iterator<std::string>(inputStream), {});
// Show result to the user
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
}
然后下一個解決方案將單詞轉換為小寫。所以,我不得不寫4個陳述句。請參閱下面的第二個解決方案。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cctype>
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputStream{ "r:\\input.txt" }; inputStream) {
std::vector<std::string> words{};
// Read all words from the file and convert to lower case
std::transform(std::istream_iterator<std::string>(inputStream), {}, std::back_inserter(words),
[](std::string w) { for (char& c : w) c = std::tolower(c); return w; });
// Show result to the user
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
}
如果不需要存盤資料,我們可以想出一個 2-statement 版本。
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputStream{ "r:\\input.txt" }; inputStream) {
// Read all words from the file and convert to lower case and output it
std::transform(std::istream_iterator<std::string>(inputStream), {}, std::ostream_iterator<std::string>(std::cout, "\n"),
[](std::string w) { for (char& c : w) c = std::tolower(c); return w; });
}
}
有時教師希望學生使用指標學習動態記憶體管理。
但是強烈建議不要使用擁有記憶體的指標。在std::vector已發明了這個原因,在十多年前。
無論如何,我還將展示一個使用new. 它有效,但您不應該使用它。
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputStream{ "r:\\input.txt" }; inputStream) {
// Do some initial allocation of memory
std::string* words = new std::string[1]{};
unsigned int numberOfAvaliableSlotsInDynamicArray{1};
// Now we want to read words. We want also to count the words,so that we can allocate appropriate memory
std::string word{};
unsigned int wordCounter{};
// Read all words in a loop
while (inputStream >> word) {
// Check, if we still have enough space in our dynamic array
if (wordCounter >= numberOfAvaliableSlotsInDynamicArray) {
// Oh, we are running out of space. Get more memory
numberOfAvaliableSlotsInDynamicArray *= 2;
std::string* temp = new std::string[numberOfAvaliableSlotsInDynamicArray]{};
// Copy all existing data into new array
for (unsigned int i{}; i < wordCounter; i)
temp[i] = words[i];
// Delete old memory
delete[] words;
// And assign new storage to words
words = temp;
}
// STore the recently read word at the end of the array
words[wordCounter] = word;
// Count words. Now we have one word more
wordCounter;
}
// Now we have read all words from the file. Show output
for (unsigned int i{}; i < wordCounter; i)
std::cout << words[i] << '\n';
// Release memory
delete[] words;
}
}
甚至智能指標,如果有的話,應該用作指標,也不好。
此外,不應使用以下內容。
#include <iostream>
#include <fstream>
#include <string>
#include <memory>
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputStream{ "r:\\input.txt" }; inputStream) {
// Do some initial allocation of memory
std::unique_ptr<std::string[]> words = std::unique_ptr<std::string[]>(new std::string[1]);
unsigned int numberOfAvaliableSlotsInDynamicArray{ 1 };
// Now we want to read words. We want also to count the words,so that we can allocate appropriate memory
std::string word{};
unsigned int wordCounter{};
// Read all words in a loop
while (inputStream >> word) {
// Check, if we still have enough space in our dynamic array
if (wordCounter >= numberOfAvaliableSlotsInDynamicArray) {
// Oh, we are running out of space. Get more memory
numberOfAvaliableSlotsInDynamicArray *= 2;
std::unique_ptr<std::string[]> temp = std::unique_ptr<std::string[]>(new std::string[numberOfAvaliableSlotsInDynamicArray]);
// Copy all existing data into new array
for (unsigned int i{}; i < wordCounter; i)
temp[i] = std::move(words[i]);
// And assign new storage to words
words = std::move(temp);
}
// STore the recently read word at the end of the array
words[wordCounter] = word;
// Count words. Now we have one word more
wordCounter;
}
// Now we have read all words from the file. Show output
for (unsigned int i{}; i < wordCounter; i)
std::cout << words[i] << '\n';
}
}
結論:使用std::vector.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/346330.html
