[英]Reading a text file using stdin then traversing through multiple arrays
I got a text file that is a single line of a string. 我有一个文本文件,它是字符串的单行。 For example: 例如:
I'm John 我是约翰
I need to read the file using stdin then traverse each characters into multiple arrays where each row shifts to the left by one character: 我需要使用stdin读取文件,然后将每个字符遍历为多个数组,其中每行向左移动一个字符:
row1 = [I, ' , m , , J , o , h , n] row1 = [I,',m,,J,o,h,n]
row2 = [' , m , , J, o , h, n , I ] row2 = [',m,,J,o,h,n,I]
row3 = [m , , J , o , h, n, I , ' ] row3 = [m,,J,o,h,n,I,']
row4 = [, , J , o , h , n , I , ' , m] row4 = [,,J,o,h,n,I,',m]
... ...
rown = [n , I , ' , m , , J , o , h ] rown = [n,I,',m,,J,o,h]
It is important to note the length of the arrays and number of arrays I create are variable that are dependent on the length of the string from the text file (n*n). 重要的是要注意数组的长度和我创建的数组的数量是变量,取决于文本文件中字符串的长度(n * n)。 In this case it would be 8*8 characters, so I need to create 8 arrays with 8 length each. 在这种情况下,它将是8 * 8个字符,因此我需要创建8个数组,每个数组的长度为8。 Any help please? 有什么帮助吗?
I would read the data into an std::string
. 我将数据读入std::string
。
I'd create an std::vector<std::string>
to hold all the results. 我将创建一个std::vector<std::string>
来保存所有结果。
I'd use the vector's push_back
member to append a string to the vector. 我会使用向量的push_back
成员将字符串追加到向量。
Then I'd use std::rotate
to rotate the string by one character. 然后,我将使用std::rotate
rotate将字符串旋转一个字符。
I'd repeat appending and rotating for as many characters as the string contains. 我重复添加和旋转字符串所包含的尽可能多的字符。
Jerry is correct and gives a crisp solution to your problem. 杰里是正确的,可以为您的问题提供清晰的解决方案。 You can perhaps have it better using std::vector<std::vector<char> >
to hold the data and doing something like: 您也许可以使用std::vector<std::vector<char> >
更好地保存数据并执行以下操作:
int i = 0;
do
{
for (int j = 0; j < len; j++)
{
data[i][j] = input[(i+j)/len];
}
} while (i++ < len) // len is 8 in your case
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.